You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件使用setInterval时出现‘Can't perform a React state update on an unmounted component’警告的解决求助

Fixing "Can't perform a React state update on an unmounted component" Warning

Hey there! Let's tackle that frustrating warning you're seeing. The root issue here is that your setInterval keeps running even after your component unmounts, and when it tries to call setDateState, React freaks out because the component no longer exists in the DOM.

Let's break down why your initial fix didn't work:

  • You declared mount inside the useEffect, but tried to set isMounted = false in the cleanup function (that's a typo—should be mount = false).
  • Even if you fixed that typo, you never actually stopped the interval from running. The mount flag might prevent the state update, but the interval itself would keep ticking in the background, wasting memory and still risking issues.

Here's the corrected version that fixes both problems:

function Timer() { 
  const [dateState, setDateState] = useState(new Date()); 

  useEffect(() => { 
    let mounted = true;
    // Store the interval ID so we can clear it later
    const timerId = setInterval(() => {
      // Only update state if the component is still mounted
      if (mounted) {
        setDateState(new Date());
      }
    }, 1000); 

    // Cleanup function runs when the component unmounts
    return () => {
      mounted = false;
      clearInterval(timerId); // Stop the interval entirely
    }; 
  }, []); 

  return( 
    <div className="container"> 
      <p className="text-end text-danger">{dateState.toLocaleDateString('fr-BE' , { day : 'numeric', month : 'short', year: 'numeric' })}</p> 
      <div className="text-center"> 
        <h3 className="text-info"> 
          {dateState.toLocaleString('fr-BE', { hour: 'numeric', minute: 'numeric', second : 'numeric', hour24: true })} 
        </h3> 
      </div> 
    </div> 
  ) 
} 
export default Timer;

Key fixes explained:

  • Save the interval ID: By assigning setInterval to timerId, we can use clearInterval(timerId) in the cleanup function to completely stop the interval when the component unmounts. This eliminates the source of the problem.
  • Mounted flag as a safety net: Even if something goes wrong with clearing the interval (unlikely, but better safe than sorry), we check if mounted is true before updating state—so React never tries to update state on an unmounted component.
  • Proper cleanup: The return function in useEffect runs when the component unmounts, so we set mounted to false and clear the interval here to clean up all resources.

This should get rid of that warning entirely and also prevent any memory leaks from the lingering interval.

内容的提问来源于stack exchange,提问作者Mishimaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 09:47:40