python
runtime_error
ai_generated
true
运行时错误:不能在同步上下文中使用异步生成器。
RuntimeError: You cannot use async generator in sync context
ID: python/fastapi-async-sync-mixing
80%修复率
84%置信度
0证据数
2024-06-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在 FastAPI 依赖或路由处理器中错误地混合异步和同步代码,例如在同步端点中调用异步函数。
English
Mixing async and sync code incorrectly in FastAPI dependencies or route handlers, e.g., calling async functions from sync endpoints.
解决方案
-
95% 成功率
Define endpoint as async def if using async functions: @app.get('/') async def read_root(): result = await some_async_function() -
90% 成功率
Use anyio.to_thread.run_sync for sync functions in async context: from anyio import to_thread result = await to_thread.run_sync(sync_function)
无效尝试
常见但无效的做法:
-
90% 失败
asyncio.run() cannot be called from a running event loop; causes RuntimeError.
-
85% 失败
Calling async function returns coroutine object, not result; must be awaited.