无法在已卸载的组件上调用setState(或forceUpdate).这是空操作,但表示您的应用程序中发生内存泄漏 [英] Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application

查看:47
本文介绍了无法在已卸载的组件上调用setState(或forceUpdate).这是空操作,但表示您的应用程序中发生内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会出现此错误?

警告:无法在已卸载的设备上调用setState(或forceUpdate)成分.这是空操作,但表示您的内存泄漏应用.要修复,请取消所有订阅和异步任务在componentWillUnmount方法中.

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

postAction.js

export const getPosts = () => db.ref('posts').once('value');

组件:

constructor(props) {
  super(props);
  this.state = { posts: null };
}

componentDidMount() {
  getPosts()
    .then(snapshot => {
      const result = snapshot.val();
      this.setState(() => ({ posts: result }));
    })
    .catch(error => {
      console.error(error);
    });
}

componentWillUnmount() {
  this.setState({ posts: null });
}

render() {
  return (
    <div>
      <PostList posts={this.state.posts} />
    </div>
  );
}

推荐答案

正如其他人提到的那样,componentWillUnmount中的setState是不必要的,但它不会引起您所看到的错误.相反,可能的罪魁祸首是以下代码:

As others mentioned, the setState in componentWillUnmount is unnecessary, but it should not be causing the error you're seeing. Instead, the likely culprit for that is this code:

componentDidMount() {
  getPosts()
    .then(snapshot => {
      const result = snapshot.val();
      this.setState(() => ({ posts: result }));
    })
    .catch(error => {
      console.error(error);
    });
}

由于getPosts()是异步的,因此在可以解析之前,组件可能已卸载.您无需进行检查,因此.then可以在卸载组件后最终运行.

since getPosts() is asynchronous, it's possible that before it can resolve, the component has unmounted. You're not checking for this, and so the .then can end up running after the component has unmounted.

要处理此问题,可以在willUnmount中设置一个标志,然后在.then中检查该标志:

To handle that, you can set a flag in willUnmount, and check for that flag in the .then:

componentDidMount() {
  getPosts()
    .then(snapshot => {
      if (this.isUnmounted) {
        return;
      }
      const result = snapshot.val();
      this.setState(() => ({ posts: result }));
    })
    .catch(error => {
      console.error(error);
    });
}

componentWillUnmount() {
  this.isUnmounted = true;
}

这篇关于无法在已卸载的组件上调用setState(或forceUpdate).这是空操作,但表示您的应用程序中发生内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆