# 运行时错误：ContextVar 'context'已经存在

- **ID:** `python/fastapi-runtimeerror-starlette-context-already-exists`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在同一作用域中重复声明了ContextVar，通常是由于中间件或依赖注入冲突。

## 版本兼容性

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

## 解决方案

1. **Remove duplicate ContextVar declaration** (90% 成功率)
   ```
   Ensure only one declaration: from contextvars import ContextVar
context = ContextVar('context', default=None)
   ```
2. **Use a single ContextVar across modules** (85% 成功率)
   ```
   Create a shared module for ContextVar and import it.
   ```

## 无效尝试

- **Ignoring the error and retrying** — ContextVar conflict persists until code is fixed. (90% 失败率)
- **Using different variable names without understanding** — Root cause is duplicate declaration, not name. (60% 失败率)
