# 运行时错误：不能在同步上下文中使用异步生成器

- **ID:** `python/fastapi-async-sync-mixing-error`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

错误地混合异步和同步代码，例如在同步路由中使用异步生成器。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   Define the route as async if you need to use async generators: @app.get('/')\nasync def read_root():\n    async for item in async_gen():\n        yield item
   ```
2. **** (80% 成功率)
   ```
   For sync routes, use a sync generator or collect items with asyncio.run() in a separate function.
   ```

## 无效尝试

- **** — Adding asyncio.run() inside a sync route can cause event loop conflicts. (80% 失败率)
- **** — Converting an async generator to a list with list() works only in async context, not sync. (70% 失败率)
