# RuntimeError: 超时上下文管理器应在任务内部使用

- **ID:** `python/asyncio-timeout-no-current-event-loop`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

asyncio.timeout()（3.11+）或 asyncio.wait_for() 在 Task 上下文之外使用，例如直接在 loop.run_until_complete() 中调用而未用 create_task 包装。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.11+ | active | — | — |
| 3.12+ | active | — | — |

## 解决方案

1. **** (93% 成功率)
   ```
   task = asyncio.create_task(do_work())
try:
    async with asyncio.timeout(5):
        await task
except TimeoutError:
    task.cancel()
   ```
2. **** (92% 成功率)
   ```
   try:
    result = await asyncio.wait_for(do_work(), timeout=5)
except asyncio.TimeoutError:
    ...
   ```

## 无效尝试

- **** — Blocks the loop and defeats async concurrency. (90% 失败率)
- **** — Debug flag is unrelated; the check is unconditional. (85% 失败率)
