解决: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);
    }

搞定!

 

posted @ 2020-11-19 15:14  学富五车  阅读(1147)  评论(0编辑  收藏  举报