python
runtime_error
ai_generated
true
RuntimeError: 事件循环已关闭。
RuntimeError: Event loop is closed
ID: python/starlette-event-loop-closed
80%修复率
85%置信度
0证据数
2024-08-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.30+ | active | — | — | — |
根因分析
在某个事件循环中创建的异步资源(如 aiohttp/httpx 客户端、数据库连接池)在该循环关闭后被复用,常见于测试用例或热重载。
English
Async resources (e.g., aiohttp/httpx client, DB pool) created in one event loop are reused after that loop is closed, often across test cases or reloads.
解决方案
-
92% 成功率
from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app): app.state.client = httpx.AsyncClient() yield await app.state.client.aclose() app = FastAPI(lifespan=lifespan) -
90% 成功率
async with httpx.AsyncClient() as client: r = await client.get(url)
无效尝试
常见但无效的做法:
-
80% 失败
Replaces loop but leaves stale client bound to old loop.
-
95% 失败
Buffering setting irrelevant to event loop lifecycle.