React setTimeout - 内存泄漏

upo*_*pog 4 javascript memory-leaks reactjs

我有下面的组件,我在其中显示消息 5 秒,然后将其从主页中删除。

当我在页面之间切换时,有时会遇到以下错误。有什么建议请

    index.js:1 Warning: Can't perform a React state update 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 a useEffect cleanup function.
Run Code Online (Sandbox Code Playgroud)

代码:

 const Home = props => {
    
      const [visible, setVisible] = useState(true);
    
       useEffect(() => {
        setTimeout(() => setVisible(false), 5000);
      }, []); 
    
      return (
       <div >
         {visible && <Message showDefault={false}  /> }
         <BaseView  />
    
       </div> 
        
        );
    };
Run Code Online (Sandbox Code Playgroud)

rai*_*7ow 7

setTimeout好吧,这个错误实际上是不言自明的:在组件已经卸载后,调用 触发的状态更改函数。但这是变相的无操作:组件不再渲染,为什么有人会对它的内部状态变化感兴趣?

值得庆幸的是,React 提供了一种记录在案的方法来清理这些和类似的异步状态更改器 - 通过使用回调返回的函数useEffect。像这样:

useEffect(() => {
  const timeoutId = setTimeout(() => setVisible(false), 5000);
  return function cleanup() {
    clearTimeout(timeoutId);
  }
}, []);
Run Code Online (Sandbox Code Playgroud)

请注意,该函数不必命名(但它稍微简化了阅读)。

  • 另请参阅:[清理效果](https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup) (2认同)