python
runtime_error
ai_generated
true
运行时错误:不能在同步上下文中使用异步生成器
RuntimeError: You cannot use async generator in sync context
ID: python/fastapi-async-sync-mixing-error
80%修复率
84%置信度
0证据数
2024-08-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
错误地混合异步和同步代码,例如在同步路由中使用异步生成器。
English
Mixing async and sync code incorrectly, such as using an async generator in a synchronous route or vice versa.
解决方案
-
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 -
80% 成功率
For sync routes, use a sync generator or collect items with asyncio.run() in a separate function.
无效尝试
常见但无效的做法:
-
80% 失败
Adding asyncio.run() inside a sync route can cause event loop conflicts.
-
70% 失败
Converting an async generator to a list with list() works only in async context, not sync.