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

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

## 根因

在 FastAPI 依赖或路由处理器中错误地混合异步和同步代码，例如在同步端点中调用异步函数。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   Define endpoint as async def if using async functions: @app.get('/')
async def read_root():
    result = await some_async_function()
   ```
2. **** (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)
   ```

## 无效尝试

- **** — asyncio.run() cannot be called from a running event loop; causes RuntimeError. (90% 失败率)
- **** — Calling async function returns coroutine object, not result; must be awaited. (85% 失败率)
