# context 已取消

- **ID:** `go/context-canceled-in-goroutine`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

上下文被取消（由于超时、截止时间或显式取消），而某个 goroutine 仍在使用它。该 goroutine 从遵循上下文的函数中收到 context.Canceled 错误。

## 版本兼容性

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

## 解决方案

1. **** (98% 成功率)
   ```
   select {
case <-ctx.Done():
    return ctx.Err()
default:
    // continue
}
   ```
2. **** (95% 成功率)
   ```
   ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
   ```

## 无效尝试

- **** — Ignoring cancellation can lead to resource leaks, wasted work, and violating the contract of context-aware functions. (95% 失败率)
- **** — This loses the cancellation signal and any deadlines, potentially causing the goroutine to run indefinitely. (90% 失败率)
