# setState() 在 dispose() 后调用：_MyWidgetState#abcde（生命周期状态：已失效，未挂载）

- **ID:** `flutter/setstate-after-dispose`
- **领域:** flutter
- **类别:** lifecycle_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

有状态小部件的 setState() 在小部件已从树中移除并释放后被调用，通常是由于异步回调在释放后完成。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Flutter 3.16 | active | — | — |
| Dart 3.2 | active | — | — |
| Android SDK 33 | active | — | — |
| iOS 16 | active | — | — |

## 解决方案

1. ```
   在异步代码中调用 setState() 前检查 'mounted' 属性。
   ```
2. ```
   在 dispose() 方法中取消订阅或 future，以防止回调触发。
   ```
3. ```
   如果小部件应在导航中保持存活，使用带有 AutomaticKeepAliveClientMixin 的 StatefulWidget。
   ```

## 无效尝试

- **Calling setState() in a try-catch block and ignoring the error** — Does not prevent the call; the error still occurs and may cause undefined behavior. (80% 失败率)
- **Wrapping setState() in a timeout to delay execution** — Delay does not guarantee the widget is still mounted; race condition remains. (60% 失败率)
- **Using a global flag to skip setState() without checking mounted** — Global flags are error-prone and may miss widget-specific lifecycle states. (50% 失败率)
