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

Reactjs·Sep 13, 2026·beginner·
Quick answer

An async operation (a fetch, a timer) that was started while the component was mounted resolved after the component had already unmounted, and its `.then()`/callback still tries to call a state setter. Cancel the operation in your effect's cleanup function, or guard the setter with a mounted check, so the callback is a no-op after unmount.

What causes this error

A promise or timer doesn't know or care whether the component that started it is still on screen by the time it resolves. If a `fetch().then(setData)` or a `setTimeout` callback fires after the user has navigated away or the component was otherwise unmounted, calling the setter on a component that no longer exists produces this warning — and can mask a real memory leak if the underlying request keeps running unnecessarily.

The Fix

// Wrong — no cancellation, setData can fire after unmount
useEffect(() => {
  fetch('/api/data').then((res) => res.json()).then(setData);
}, []);

// Fix — cancel the request via AbortController in cleanup
useEffect(() => {
  const controller = new AbortController();
  fetch('/api/data', { signal: controller.signal })
    .then((res) => res.json())
    .then(setData)
    .catch((err) => {
      if (err.name !== 'AbortError') throw err;
    });
  return () => controller.abort();
}, []);

Common causes / variations

  • A `fetch` or timer with no cleanup, cancellation, or mounted-check guard
  • Navigating away quickly (e.g. clicking through a list) before a slow request resolves
  • A WebSocket or subscription callback firing after `unsubscribe()` should have already run in cleanup but didn't

Related errors

See also: useEffect runs twice in development, Cannot update a component while rendering a different component.

Was this fix helpful?

Comments

Loading comments...