# 运行时错误：响应开始后无法修改响应头

- **ID:** `python/starlette-response-headers-set-after-start`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在响应已发送给客户端后尝试设置或修改响应头（如在后台任务或流式响应中yield之后）。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   Set all headers before returning the response object, e.g., `response.headers['X-Custom'] = 'value'` before returning.
   ```
2. **** (90% 成功率)
   ```
   If using streaming, set headers in the initial response object before streaming begins.
   ```

## 无效尝试

- **** — Modifying headers in a `finally` block after the response is sent still raises the error. (90% 失败率)
- **** — Using a middleware to modify headers after the endpoint has returned doesn't work because the response is already committed. (85% 失败率)
