# RuntimeError: 事件循环已关闭

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

## 根因

在一个事件循环中创建的异步资源（httpx.AsyncClient、aiohttp session）在该循环关闭后被复用，常见于测试或重载场景。

## 版本兼容性

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

## 解决方案

1. **** (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()
   ```
2. **** (85% 成功率)
   ```
   Use pytest-asyncio with a single loop fixture for tests.
   ```

## 无效尝试

- **** — Creates a fresh loop but existing clients bound to the old loop still fail. (75% 失败率)
- **** — Subsequent requests hang or raise again on the closed loop. (80% 失败率)
