一、問題場景
網絡請求成功前退出了頁面,該 State 被從對象樹卸載掉,而這時回調了網絡請求的方法,方法中帶有 setState 的調用,也就導致了該問題。
二、問題原因
State 對象被從對象數卸載釋放之后再次調用 setState 就會報 setState() called after dispose()。
二、解決方案
State 的 mounted 源碼:
/// Whether this [State] object is currently in a tree.
///
/// After creating a [State] object and before calling [initState], the
/// framework "mounts" the [State] object by associating it with a
/// [BuildContext]. The [State] object remains mounted until the framework
/// calls [dispose], after which time the framework will never ask the [State]
/// object to [build] again.
///
/// It is an error to call [setState] unless [mounted] is true.
bool get mounted => _element != null;
注釋中說得很清楚:判斷 State 對象現在還在不在對象數中。
So,解決方案就是在 setState 之前先判斷一下該 State 是否已經被釋放:
/// 更新用戶狀態
void updateState(fn){
if (mounted) {
setState(fn);
}
搞定!