解決:setState() called after dispose() 內存泄漏問題


一、問題場景

網絡請求成功前退出了頁面,該 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);
    }

搞定!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM