patternjavascriptMajor
AbortController: Cancel Fetch Requests on Component Unmount or Timeout
Viewed 0 times
abortcontrollerfetch cancelcleanupmemory leakreact unmountsignal
Error Messages
Problem
Fetch requests continue running after a React component unmounts, then attempt to call
setState on an unmounted component, causing memory leaks and the warning: 'Can't perform a React state update on an unmounted component'.Solution
Create an AbortController in useEffect, pass its signal to fetch, and abort in the cleanup function.
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const res = await fetch('/api/data', { signal: controller.signal });
const data = await res.json();
setData(data);
} catch (err) {
if (err.name === 'AbortError') return; // expected, not an error
setError(err);
}
}
load();
return () => controller.abort();
}, []);Why
AbortController sends a signal through the fetch call that the browser's network stack listens to. When abort() is called, any pending promise rejects with an AbortError immediately.
Gotchas
- AbortError is a DOMException, not a standard Error — check
err.name === 'AbortError', noterr instanceof AbortError. - You can reuse the same controller for multiple fetches — aborting once cancels all of them.
- fetch does not abort already-sent requests at the network level in all environments; it stops the response processing.
- Node.js 18+ supports AbortController natively in the fetch API.
Revisions (0)
No revisions yet.