解决:setState() called after dispose() 内存泄漏问题
Posted maqingyuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决: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);
}
搞定!
以上是关于解决:setState() called after dispose() 内存泄漏问题的主要内容,如果未能解决你的问题,请参考以下文章
[踩坑]Flutter使用setState出错call setState() on a State object for a widget that no longer appears in th
[踩坑]Flutter使用setState出错call setState() on a State object for a widget that no longer appears in th
[踩坑]Flutter使用setState出错call setState() on a State object for a widget that no longer appears in th
[React] Call setState with null to Avoid Triggering an Update in React 16