Cancelling API Requests in Vue 3: One Registry, Two Paths, and the Question That Orders Them
Vue 3 exposes four things that look like four ways to cancel a stale request — the watch/watchEffect onCleanup parameter, the 3.5 onWatcherCleanup import, and AbortController. They're really two registration paths over one registry, and one of them silently no-ops after await. Here's the source-level reason, and which to reach for.
Vue 3 exposes four things that look like four separate ways to cancel a stale request. The onCleanup parameter that watchEffect passes to its effect. The same parameter that watch passes to its callback. The onWatcherCleanup import shipped in Vue 3.5. And the AbortController that does the actual cancelling. They are not four ways — they are two registration paths over one cleanup registry, plus the single object that aborts the request. And one of those two paths silently stops working the instant an await runs: no exception, no production warning, just a stale request that resolves on its own schedule and overwrites fresher data. The fix isn't a newer API. It's knowing which path survives the await.
The three costs of a request nobody cancelled
Three different things break when a request outlives its relevance, and they are not one problem wearing three hats. Treating cancellation as a performance nicety dismisses the first one, which is the one that draws blood.
That first cost is correctness. A search field is bound to a watch; every keystroke fires a request. The user types k, ki, kit, kitt, kitten, kittens — six requests, six round-trips, no guarantee they return in order. The request for kit hits a slow replica and lands last. The watcher's callback runs with the kit payload, overwrites the kittens results already on screen, and the dashboard now shows results for a query the user finished typing two seconds ago. The URL still says kittens. Nothing threw. The official docs name this exact race: "what if id changes before the request completes? When the previous request completes, it will still fire the callback with an ID value that is already stale" (Vue watchers guide).
The second cost is wasted work, and it scales with traffic. Every abandoned request still ran. The browser opened the connection, the server ran the query, the bytes crossed the wire. One stale search is free. A dashboard that re-fires on every filter change, parked on a second monitor all day, is a steady drip of work nobody will read — bandwidth on the client, CPU and connection-pool slots on the server.
The third cost is resource lifetime, and it's the quietest. A request in flight pins memory until it settles: the promise, its closure, and the response-body buffer once headers arrive — all reachable, none collectable, until the fetch resolves or rejects.
One clarification before the mechanism, because the search-as-you-type framing invites it: cancellation is not debounce. Debounce decides whether to fire a request; cancellation decides what to do with the ones already in flight. They compose — debounce thins a storm of keystrokes to one request per pause, cancellation kills the previous request when the next one does fire — and a real search box usually wants both. Request deduplication (collapsing identical in-flight requests into one) is the third companion, and the library section below gets it for free. The other place reactive fetching lives — <Suspense> with an async setup() — has its own cancellation story and stays out of scope here.
The patterns that lost to AbortController
Browser request cancellation has a short, tangled history, and the current advice rests on knowing which of the old patterns to stop reaching for. XMLHttpRequest carried .abort() from the start — but almost nobody writes against XHR directly anymore. Axios shipped its own CancelToken, then deprecated it in 0.22 in favor of AbortController; code still carrying CancelToken is the clearest sign a cancellation path predates 2021 and is overdue for migration. Then there's the pattern that never went through a deprecation because it was never really an API: the staleness flag.
Plenty of hand-rolled search boxes still endorse the flag, and it's wrong in a way that matters. Watch the guard on the last line — it gates the render, not the request:
let latest = 0
watch(searchTerm, async (term) => {
const requestId = ++latest
const res = await fetch(`/api/search?q=${term}`)
const data = await res.json()
if (requestId === latest) results.value = data // stale responses get dropped here
})
The flag fixes correctness and nothing else. The stale request still ran to completion — the connection opened, the server did the work, the buffer filled — so two of the three costs survive. This article rejects the flag for exactly that reason. AbortController addresses all three, because it cancels the request itself rather than ignoring the answer. The one line readers misjudge is the catch:
watch(searchTerm, async (term, _prev, onCleanup) => {
const controller = new AbortController()
onCleanup(() => controller.abort())
try {
const res = await fetch(`/api/search?q=${term}`, { signal: controller.signal })
results.value = await res.json()
} catch (err) {
if (err.name !== 'AbortError') throw err // aborting rejects the promise; that's expected, rethrow the rest
}
})
Aborting an in-flight fetch rejects its promise with an AbortError, so the catch has to let that specific error pass and rethrow everything else — skip it and every cancellation surfaces as an unhandled rejection. The pre-3.5 Nuxt recipe wired the same AbortController into useAsyncData and exposed a manual cancel function — same primitive, more plumbing.
With the canceller settled — it's AbortController, everywhere, now the de facto cleanup idiom — the only open question is where the controller.abort() registration lands so it actually fires. That's where the four names come in, and where 3.5 added a second path with a sharp edge.
Four names, two registration paths, one registry
Here is the whole map before the zoom-in. The four names collapse into three roles:
- The canceller.
AbortControllerand itssignal. The only thing that actually stops a request. Settled above. - The parameter path.
watchEffectpasses anonCleanupfunction as the first argument of its effect;watchpasses the identical function as the third argument of its callback. Same function, same registry, two entry points — one per watcher API. - The import path.
onWatcherCleanup, imported fromvue, added in 3.5. It registers into the same registry as the parameter, but finds its watcher a different way — and that difference is the whole article.
The signatures, from the reactivity API reference, show the shape but not the catch:
function watchEffect(
effect: (onCleanup: OnCleanup) => void,
options?: WatchEffectOptions
): WatchHandle
type OnCleanup = (cleanupFn: () => void) => void
function onWatcherCleanup(
cleanupFn: () => void,
failSilently?: boolean
): void
Both paths register the same kind of callback: something that runs right before the watcher re-runs, and again when the watcher is stopped. The onCleanup parameter and onWatcherCleanup are not alternatives with different powers — they are two doors into one room. The rest of this piece is about why one of the doors is sometimes locked.
The cleanup registry, under the hood
Inside packages/reactivity/src/watch.ts, the cleanup callbacks for every watcher live in one structure (Vue core source). The key is the part to notice:
const cleanupMap: WeakMap<ReactiveEffect, (() => void)[]> = new WeakMap()
A WeakMap keyed by the effect, holding an array of cleanup functions per watcher. Because the key is the effect itself, the whole entry is garbage-collected when the watcher is — the registry can't leak the cleanups it holds. Register a cleanup and it's pushed onto that watcher's array. When the watcher re-runs, the array drains first; the source comment is blunt about it — "cleanup before running cb again." When the watcher is disposed, the same array runs through the effect's onStop. That's the entire lifecycle: run before next, run on stop.
Here's the toy version — one watchEffect, the cleanup wired through the first-argument parameter, no error handling or result use because the only thing on display is the wiring:
import { watchEffect } from 'vue'
watchEffect((onCleanup) => {
const controller = new AbortController()
onCleanup(() => controller.abort()) // load-bearing: register the abort the instant the controller exists
fetch(`/api/user/${userId.value}`, { signal: controller.signal })
})
Every time userId changes, watchEffect re-runs: it drains the previous cleanup — which aborts the prior request — then runs the effect again with a fresh controller. The onCleanup parameter here is a closure. When watchEffect invokes the effect, it hands in a function that already knows which watcher it belongs to, because it was created bound to that watcher. Hold onto that word — bound. It's the difference between the two paths.
onWatcherCleanup stops working after the first await
onWatcherCleanup registers into that same array. It finds its watcher through a different mechanism, and that mechanism has an expiry. The docs admit the limit in a parenthetical: onWatcherCleanup "can only be called during the synchronous execution of a watchEffect effect function or watch callback function (i.e. it cannot be called after an await statement in an async function)" (reactivity API reference).
The reason is one module-level variable. In watch.ts, onWatcherCleanup defaults its owner to activeWatcher:
export function onWatcherCleanup(
cleanupFn: () => void,
failSilently = false,
owner: ReactiveEffect | undefined = activeWatcher,
): void
activeWatcher is a single mutable binding — let activeWatcher: ReactiveEffect | undefined = undefined — that Vue sets when a watcher enters its synchronous phase and clears the moment that phase ends. A call before the first await sees the live watcher. A call after the await sees undefined, because the synchronous phase finished several microtasks ago. Watch where the registration sits relative to the await:
import { watch, onWatcherCleanup } from 'vue'
watch(userId, async (id) => {
const controller = new AbortController()
const res = await fetch(`/api/user/${id}`, { signal: controller.signal })
const profile = await res.json()
onWatcherCleanup(() => controller.abort()) // activeWatcher is already undefined — registers nothing
applyProfile(profile)
})
That call registers nothing. With failSilently at its default, Vue emits a warning — "onWatcherCleanup() was called when there was no active watcher to associate with" — and in production that warning is stripped, so the call is a pure no-op. The controller never enters the registry, the previous request is never aborted, and every cost from the first section is back on the table. This isn't hypothetical: the issue asking for a sharper warning here (vuejs/docs #3222) was opened in April 2025 and is still open, which means the runtime still won't throw and the docs note remains the only guardrail.
The blunt repair is to register during the synchronous phase, before the first await:
watch(userId, async (id) => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort()) // still inside the sync phase — registers fine
const res = await fetch(`/api/user/${id}`, { signal: controller.signal })
applyProfile(await res.json())
})
Move one line up and onWatcherCleanup behaves exactly as advertised.
None of this means 3.5 was wrong to ship the global. The onCleanup parameter carries a real ergonomic cost: it has to be threaded through the watcher's signature, and a cleanup that needs to be registered from inside a synchronous helper three calls deep can't reach the parameter unless every layer passes it down by hand. onWatcherCleanup solves precisely that — it pulls the active watcher from module state, so any synchronous code running under the watcher can register cleanup with no parameter in scope. That's a real ergonomic gain: the cleanup reads beside the effect, with nothing bolted onto the callback's signature to carry it there. The team didn't ship a worse parameter; it shipped a different tool with a different constraint, and the constraint is invisible until an await crosses it. The verdict: onWatcherCleanup is the cleaner call in synchronous code and a trap in asynchronous code — which is exactly the code doing the fetching it's most often demonstrated with.
The parameter removes the ordering question altogether. Because it's the bound closure from the previous section, the docs are explicit that it "is bound to the watcher instance so it is not subject to the synchronous constraint of onWatcherCleanup" (Vue watchers guide) — it registers correctly whether it runs before or after an await, because there's no activeWatcher for it to miss.
Where a library earns the dependency
The strongest case against everything above is short: don't hand-roll cancellation at all. A data-fetching library already owns the registry, the signal, and the dedup, and a search box is the exact use case those libraries were built for. The counter insists the primitive is a waste of attention — and for the search box, it's mostly right.
VueUse's useFetch wraps an AbortController and re-runs on reactive source changes. The one option that matters for cancellation is refetch: set it true and the previous request aborts automatically whenever the URL ref changes (VueUse useFetch). The signal threading from the earlier examples disappears — the library does it:
import { useFetch } from '@vueuse/core'
const url = computed(() => `/api/search?q=${searchTerm.value}`)
const { data } = useFetch(url, { refetch: true }).json() // aborts the in-flight request when `url` changes
That's genuinely less code than the hand-rolled watcher, and it folds in request deduplication for free. useFetch also exposes abort, canAbort, and aborted for wiring a manual Stop button — a different interaction than search-as-you-type, so it stays a mention rather than a contrived demo here.
TanStack Query (via @tanstack/vue-query) argues the same position from the other end: it hands an AbortSignal to every query function and treats that signal as the universal cancellation contract. The catch is the default. TanStack does not cancel on change or unmount unless the query function actually forwards the signal it's handed (TanStack Query cancellation):
import { useQuery } from '@tanstack/vue-query'
useQuery({
queryKey: ['search', searchTerm],
queryFn: ({ signal }) => fetch(`/api/search?q=${searchTerm.value}`, { signal }).then(r => r.json()), // forward `signal` or nothing cancels
})
So "the library makes it automatic" is half true: automatic that the signal exists, manual that it's used. That's the seam in the counter. The primitive's defenders concede the search box to the library — when the app already depends on one, or when the use case wants the cache, dedup, and retry machinery that rides along, reaching for useFetch or TanStack is the right call. The line holds where the alternative is adding a data-fetching dependency to abort a single fetch, or where the code needs control the wrapper doesn't expose: the watcher's flush timing, a non-fetch cancellable, cleanup sequenced against other effects. The primitive is small. Owning it is not the sin the counter implies — provided the registration lands where it fires.
The decision rule
Every choice above reduces to one question: is the controller.abort() registration still running inside the watcher's synchronous phase? If yes, any path works — pick on ergonomics. Once the registration has crossed an await, only the bound parameter survives. Everything else the docs dwell on — flush timing, the failSilently flag, getCurrentWatcher — the rule dismisses as secondary.
In general: AbortController is the canceller; the only real decision is where the abort() registration runs — and it has to run before the first await, or use the path that doesn't care.
- Synchronous registration (no
awaitbefore it) — reach foronWatcherCleanup; it's the cleanest call and threads no parameter.AvoidJavaScript// pre-3.5 plumbing: a separate ref plus a second watcher just to abort const controller = ref() watch(id, () => { controller.value?.abort() controller.value = new AbortController() })PreferJavaScriptwatch(id, () => { const controller = new AbortController() onWatcherCleanup(() => controller.abort()) // co-located, sync phase }) - Registration after an
await— reach for theonCleanupparameter; it's bound to the watcher instance, so it survives the async gap that strandsonWatcherCleanup.AvoidJavaScriptwatch(id, async () => { const c = new AbortController() await fetch(url, { signal: c.signal }) onWatcherCleanup(() => c.abort()) // activeWatcher gone — no-op })PreferJavaScriptwatch(id, async (v, _p, onCleanup) => { const c = new AbortController() onCleanup(() => c.abort()) // bound to the watcher; fires on the next change await fetch(url, { signal: c.signal }) }) - No appetite to own the registry — reach for a library;
useFetch({ refetch: true }), or a TanStack query that forwardssignal, is the sameAbortControllerwith the bookkeeping hidden.AvoidJavaScript// hand-rolling abort + dedup + retry for a plain search box let latest = 0 watch(term, async (t) => { const id = ++latest // ...controller, guard, retry by hand... })PreferJavaScriptconst { data } = useFetch(url, { refetch: true }).json() // abort-on-change, built in
The three cases are three distinct fixes, not three flavors of one: co-locate in synchronous code, thread the parameter across async, or delegate the whole registry to a library that speaks AbortSignal.
The four names were never four decisions. They are two ways into one registry, and the registry cares about one thing only: whether the registration call ran while the watcher was still executing synchronously. onWatcherCleanup reads that state from a module variable that's already been cleared by the time an awaited fetch resolves; the onCleanup parameter carries its watcher with it and never has to look. Reach for the global in synchronous code, and the parameter the instant an await enters the picture. The bug was never the request that wouldn't cancel. It was the cleanup registered to a watcher that had already left the room.
Sources
- Nuxt docs — useAsyncData — the
useAsyncDatacomposable the pre-3.5 Nuxt cancel recipe wraps with anAbortControllersignal. - TanStack Query — Query Cancellation —
AbortSignal-as-contract design and the opt-in default (no cancel unless the signal is forwarded). - Vue 3.5 release announcement (Vue team, September 2024) — introduction of
onWatcherCleanupas a globally imported API. - Vue core source — packages/reactivity/src/watch.ts —
cleanupMap,activeWatcher, theonWatcherCleanupsignature, and the no-active-watcher warning. - Vue docs — Reactivity API: Core —
watchEffect/onWatcherCleanupsignatures and the synchronous-execution constraint. - Vue docs — Watchers guide — the stale-request rationale and the
onCleanup-parameter instance-binding note. - vuejs/docs #3222 — onWatcherCleanup in async contexts — open issue documenting the after-
awaitfootgun. - VueUse — useFetch —
refetch: trueauto-cancel and theabort/canAbort/abortedsurface.
About the author
Eve — senior full-stack engineer (Vue / TS / Node, 8+ years).