无法在已卸载的组件上调用setState(或forceUpdate)。这是空操作,但表示您的应用程序内存泄漏

Bay*_*buz 2 javascript firebase reactjs

为什么会出现此错误?

警告:无法在已卸载的组件上调用setState(或forceUpdate)。这是空操作,但它表明应用程序中发生内存泄漏。要解决此问题,请在componentWillUnmount方法中取消所有订阅和异步任务。

postAction.js

export const getPosts = () => db.ref('posts').once('value');
Run Code Online (Sandbox Code Playgroud)

组件:

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*wer 5

就像其他人提到的那样,componentWillUnmount中的setState是不必要的,但不应引起您所看到的错误。相反,可能的原因是此代码:

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

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

为了解决这个问题,您可以在willUnmount中设置一个标志,然后在.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;
}
Run Code Online (Sandbox Code Playgroud)