# RuntimeError: 事件循环已关闭

- **ID:** `python/fastapi-asyncpg-event-loop-closed`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

asyncpg/httpx 客户端在导入时于 lifespan 之外创建；连接池绑定到已关闭的事件循环（常见于 TestClient）。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 0.100+ | active | — | — |
| 0.110+ | active | — | — |

## 解决方案

1. **** (92% 成功率)
   ```
   @asynccontextmanager
async def lifespan(app):
    app.state.pool = await asyncpg.create_pool(dsn)
    yield
    await app.state.pool.close()
app = FastAPI(lifespan=lifespan)
   ```
2. **** (85% 成功率)
   ```
   Use httpx.AsyncClient with ASGITransport for tests to keep a single loop.
   ```

## 无效尝试

- **** — Doesn't rebind existing pools; new loop still has no connections. (75% 失败率)
- **** — Lifecycle bug remains; error recurs under TestClient. (70% 失败率)
