python
runtime_error
ai_generated
true
RuntimeWarning: 协程 'send_email' 从未被 await。
RuntimeWarning: coroutine 'send_email' was never awaited
ID: python/fastapi-background-task-not-awaited
80%修复率
87%置信度
0证据数
2025-12-03首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.100.x | active | — | — | — |
| 0.110.x | active | — | — | — |
根因分析
将异步函数传给 BackgroundTasks.add_task 而未 await;或在同步路由中直接调用异步函数而未调度。
English
Passing an async function to BackgroundTasks.add_task without awaiting; or calling an async function directly in a sync route without scheduling.
解决方案
-
95% 成功率
In async route: `background_tasks.add_task(send_email, to, body)` — FastAPI awaits it after response.
-
85% 成功率
For sync routes, use a sync function or `asyncio.run(send_email(...))` (careful with loops) or offload to Celery.
无效尝试
常见但无效的做法:
-
80% 失败
Task may be cancelled when request ends; not tracked by FastAPI.
-
75% 失败
Requires a running event loop and proper thread context; often raises RuntimeError.