python
runtime_error
ai_generated
true
RuntimeError: 事件循环已关闭
RuntimeError: Event loop is closed
ID: python/fastapi-event-loop-closed
80%修复率
84%置信度
0证据数
2025-01-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在一个事件循环中创建的异步资源(httpx.AsyncClient、aiohttp session)在该循环关闭后被复用,常见于测试或重载场景。
English
Async resources (httpx.AsyncClient, aiohttp session) created in one event loop are reused after that loop closed, common in tests or reload.
解决方案
-
90% 成功率
Create clients inside lifespan and close on shutdown: @asynccontextmanager async def lifespan(app): app.state.client = httpx.AsyncClient() yield await app.state.client.aclose() -
85% 成功率
Use pytest-asyncio with a single loop fixture for tests.
无效尝试
常见但无效的做法:
-
75% 失败
Creates a fresh loop but existing clients bound to the old loop still fail.
-
80% 失败
Subsequent requests hang or raise again on the closed loop.