πŸ”§ Error Fixes
Β· 1 min read

React: Can't Perform a State Update on an Unmounted Component


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

This warning means you’re trying to update state after the component has been removed from the DOM β€” usually from an async operation that completes after navigation.

Fix 1: Cleanup in useEffect

useEffect(() => {
  let cancelled = false;
  
  fetch('/api/data')
    .then(res => res.json())
    .then(data => {
      if (!cancelled) setData(data);
    });

  return () => { cancelled = true; };
}, []);

Fix 2: Use AbortController

useEffect(() => {
  const controller = new AbortController();
  
  fetch('/api/data', { signal: controller.signal })
    .then(res => res.json())
    .then(data => setData(data))
    .catch(err => {
      if (err.name !== 'AbortError') throw err;
    });

  return () => controller.abort();
}, []);
πŸ“˜