What does abort() do in a thunk?
Short answer
In Redux Toolkit,
abort()is used to cancel the execution of an async thunk.It stops the async process (for example, a fetch) and triggers the
rejectedstate with the reason"Aborted".
Where abort() is used
The abort() method is available inside the function you pass to createAsyncThunk:
const fetchUser = createAsyncThunk(
'user/fetch',
async (id, { signal, rejectWithValue }) => {
const controller = new AbortController()
signal.addEventListener('abort', () => controller.abort())
try {
const res = await fetch(`/api/users/${id}`, { signal: controller.signal })
return await res.json()
} catch (err) {
if (err.name === 'AbortError') {
return rejectWithValue('The request was aborted')
}
throw err
}
}
)Now - if this thunk gets cancelled, RTK will call controller.abort() and the fetch will be interrupted.
How abort() works inside Redux Toolkit
When you create a thunk through createAsyncThunk, RTK adds to it:
- a special
abortControllerobject; - a
signalyou can listen to; - and an
abort()method you can call manually.
const promise = dispatch(fetchUser(5))promise is not just a plain Promise!
It has methods:
promise.abort()
promise.unwrap()Example: how to cancel an async thunk
const promise = dispatch(fetchUser(5))
// somewhere later...
promise.abort()What happens:
- Redux Toolkit calls
AbortController.abort() - All fetch requests "tied" to the
signalare interrupted - The thunk does not transition to fulfilled
- Instead, rejected fires with the error
"Aborted"
What happens under the hood
Here is, simplified, how RTK does this internally:
function createAsyncThunk(typePrefix, payloadCreator) {
return (arg) => (dispatch, getState, extra) => {
const abortController = new AbortController()
const thunkPromise = new Promise(async (resolve, reject) => {
try {
const result = await payloadCreator(arg, {
signal: abortController.signal,
dispatch,
getState,
})
dispatch({ type: `${typePrefix}/fulfilled`, payload: result })
resolve(result)
} catch (err) {
if (abortController.signal.aborted) {
dispatch({ type: `${typePrefix}/rejected`, error: 'Aborted' })
}
reject(err)
}
})
thunkPromise.abort = () => abortController.abort()
return thunkPromise
}
}Example: usage in React
const dispatch = useDispatch()
useEffect(() => {
const promise = dispatch(fetchUser(5))
return () => {
// If the component unmounts → cancel the request
promise.abort()
}
}, [dispatch])Now, if the component unmounts before the request finishes,
fetchUser will automatically be interrupted and will not try to update the state.
Why this matters
| Problem | How abort() solves it |
|---|---|
| The component unmounted during the request | Stops execution so it does not update a component that no longer exists |
| The user quickly switched tabs / pages | Old requests can be cancelled |
| A long operation needs to be cancelled | abort() instantly interrupts the thunk |
| Avoids data races ("race conditions") | Only the last active thunk keeps running |
What a cancelled thunk returns
When you call abort(), createAsyncThunk:
- dispatches the action
{ type: '.../rejected', error: { message: 'Aborted' } } - does not execute further code
- returns a Promise that rejects with the error
"Aborted"
You can catch it:
const promise = dispatch(fetchUser(5))
promise
.unwrap()
.then(data => console.log('OK', data))
.catch(err => {
if (err.name === 'AbortError') console.log('Request aborted')
})Summary
| What | Description |
|---|---|
abort() | Cancels the execution of an async thunk |
| Where it is called | On the Promise returned by dispatch(thunk()) |
| What it does | Interrupts the fetch / async function through AbortController |
| Result | Redux triggers .../rejected with the error "Aborted" |
| When it is useful | When cancelling requests, changing pages, unmounting a component |
Final summary:
The
abort()method in a thunk is used to interrupt an async operation, to avoid unnecessary state updates and data races. It works through the built-inAbortControllerpassed viasignal, and triggers the thunk's rejected state with the error"Aborted".
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.