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
mountinside the useEffect, but tried to setisMounted = falsein the cleanup function (that's a typo—should bemount = false). - Even if you fixed that typo, you never actually stopped the interval from running. The
mountflag 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
setIntervaltotimerId, we can useclearInterval(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
mountedis true before updating state—so React never tries to update state on an unmounted component. - Proper cleanup: The return function in
useEffectruns when the component unmounts, so we setmountedto 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
相关产品推荐
相关产品推荐

