# 断言错误：响应体已发送

- **ID:** `python/fastapi-assertionerror-response-body-already-sent`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在响应已经发送给客户端后尝试写入响应（例如在中间件或后台任务中）。

## 版本兼容性

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

## 解决方案

1. **Set headers before returning the response** (90% 成功率)
   ```
   response = JSONResponse(content=data, headers={'X-Custom': 'value'})
return response
   ```
2. **Use background tasks to modify response before send** (85% 成功率)
   ```
   from fastapi import BackgroundTasks
background_tasks.add_task(some_func)
   ```

## 无效尝试

- **Adding response headers after returning** — Response is immutable after being sent. (80% 失败率)
- **Using yield in streaming response incorrectly** — Multiple yields after stream ends cause assertion error. (70% 失败率)
