flutter
lifecycle_error
ai_generated
true
setState() 在 dispose() 后调用:_MyWidgetState#abcde(生命周期状态:已失效,未挂载)
setState() called after dispose(): _MyWidgetState#abcde(lifecycle state: defunct, not mounted)
ID: flutter/setstate-after-dispose
90%修复率
90%置信度
1证据数
2023-11-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Flutter 3.16 | active | — | — | — |
| Dart 3.2 | active | — | — | — |
| Android SDK 33 | active | — | — | — |
| iOS 16 | active | — | — | — |
根因分析
有状态小部件的 setState() 在小部件已从树中移除并释放后被调用,通常是由于异步回调在释放后完成。
English
A stateful widget's setState() is invoked after the widget has been removed from the tree and disposed, often due to an asynchronous callback completing after disposal.
官方文档
https://api.flutter.dev/flutter/widgets/State/setState.html解决方案
-
在异步代码中调用 setState() 前检查 'mounted' 属性。
-
在 dispose() 方法中取消订阅或 future,以防止回调触发。
-
如果小部件应在导航中保持存活,使用带有 AutomaticKeepAliveClientMixin 的 StatefulWidget。
无效尝试
常见但无效的做法:
-
Calling setState() in a try-catch block and ignoring the error
80% 失败
Does not prevent the call; the error still occurs and may cause undefined behavior.
-
Wrapping setState() in a timeout to delay execution
60% 失败
Delay does not guarantee the widget is still mounted; race condition remains.
-
Using a global flag to skip setState() without checking mounted
50% 失败
Global flags are error-prone and may miss widget-specific lifecycle states.