Skip to content

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

Error message

                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.
              

Quick summary

An async operation (fetch, setTimeout, promise) completed after the component unmounted and tried to call setState, indicating a memory leak.

Why this happens

  • An async fetch or API call resolves after the component unmounts

  • A setInterval/setTimeout callback fires after unmount

  • An event listener wasn't removed on unmount

  • A subscription wasn't cleaned up in useEffect

Minimal example

✗ Broken code
useEffect(() => {
  fetchData().then(data => setData(data)); // No cleanup!
}, []);
✓ Fixed code
useEffect(() => {
  let cancelled = false;
  fetchData().then(data => {
    if (!cancelled) setData(data);
  });
  return () => { cancelled = true; };
}, []);

The cancelled flag prevents setData from being called after unmount. The cleanup function sets it to true when the component unmounts.

How to diagnose

  • Look for async operations in useEffect without cleanup

  • Check for setInterval/setTimeout without clearInterval/clearTimeout in cleanup

  • Verify event listeners are removed in the useEffect cleanup function

How to fix

  • Add a cleanup function to useEffect that cancels the async operation

  • Use an isMounted ref to check before calling setState

  • Use AbortController to cancel fetch requests on unmount

How to prevent

  • Always return a cleanup function from useEffect when setting up subscriptions or timers

  • Use AbortController for fetch requests

Related Resources

Related Glossary

Related Lessons

  • useEffect

    Learn cleanup functions to prevent memory leaks.

← Back to language