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

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://api.flutter.dev/flutter/widgets/State/setState.html

解决方案

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

无效尝试

常见但无效的做法:

  1. 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.

  2. Wrapping setState() in a timeout to delay execution 60% 失败

    Delay does not guarantee the widget is still mounted; race condition remains.

  3. Using a global flag to skip setState() without checking mounted 50% 失败

    Global flags are error-prone and may miss widget-specific lifecycle states.