DEV Community

Eve
Eve

Posted on • Originally published at eveko.dev

Cancelling API Requests in Vue 3: One Registry, Two Paths, and the Question That Orders Them

Originally published at eveko.dev.

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 for the request that won't cancel is knowing which path survives the await, not reaching for a newer API.

The three costs of a request nobody cancelled

Three different things break when a request outlives its relevance, and they are genuinely separate problems. 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, kitte, kitten, kittens — seven requests, seven 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 throttle (a cousin of debounce that a search box rarely needs) the fourth; the library section below gets dedup for free. The other place reactive fetching lives — <Suspense> with an async setup() — has its own cancellation story and stays out of scope here, and so does SSR: on the server the lazy watch callbacks that drive these fetches never fire, so request cancellation is a client-side concern.

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 the 0.22 deprecation (October 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:

Avoid:

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
})
Enter fullscreen mode Exit fullscreen mode

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:

Prefer:

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
  }
})
Enter fullscreen mode Exit fullscreen mode

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. Where the rethrown error surfaces (an error ref set in the catch, or an onErrorCaptured above) and how the loading state is shown are the component's concern, orthogonal to cancellation and left out of these examples. 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 cancellation primitive), 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. AbortController and its signal. The only thing that actually stops a request. Settled above.
  • The parameter path. watchEffect passes an onCleanup function as the first argument of its effect; watch passes 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 from vue, 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
Enter fullscreen mode Exit fullscreen mode

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 two doors into one room. The rest of this piece is about why one of the doors is sometimes locked.

The cleanup registry, keyed by the effect

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()
Enter fullscreen mode Exit fullscreen mode

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 })
})
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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:

Avoid:

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)
})
Enter fullscreen mode Exit fullscreen mode

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", from watch.ts), 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 open issue requesting clearer docs and worked examples for this after-await footgun (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. Since even that dev-time warning vanishes in production, the one thing that still catches the bug is a test: spy on abort() to assert the prior request is cancelled, or drive the out-of-order race and assert the fresher result isn't overwritten.

The blunt repair is to register during the synchronous phase, before the first await:

Prefer:

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())
})
Enter fullscreen mode Exit fullscreen mode

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. 3.5 shipped a different tool with a different constraint, and the constraint is invisible until an await crosses it: onWatcherCleanup is the cleaner call in synchronous code and a trap in asynchronous code, exactly the code doing the fetching it's most often demonstrated with.

The parameter removes the ordering question from registration. 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
Enter fullscreen mode Exit fullscreen mode

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
})
Enter fullscreen mode Exit fullscreen mode

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 — the rule dismisses as secondary.

Best practice:

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 await before it) — reach for onWatcherCleanup; it's the cleanest call and threads no parameter.

Avoid:

  // pre-3.5 plumbing: a separate ref you abort and re-create by hand
  const controller = ref()
  watch(id, () => {
    controller.value?.abort()
    controller.value = new AbortController()
    fetch(`/api/user/${id.value}`, { signal: controller.value.signal })
  })
Enter fullscreen mode Exit fullscreen mode

Prefer:

  watch(id, () => {
    const controller = new AbortController()
    onWatcherCleanup(() => controller.abort()) // co-located, sync phase
    fetch(`/api/user/${id.value}`, { signal: controller.signal })
  })
Enter fullscreen mode Exit fullscreen mode
  • Async callback — the onCleanup parameter, registered before the first await. An await is in the picture, so the onCleanup parameter is the default over onWatcherCleanup: bound to the watcher instance, it can't be silently stranded when a registration drifts past the await the way the global is. That robustness is separate from the fix. The fix is position: the two snippets below run the identical parameter and signature, and only the registration line moves. Register it above the fetch and the abort is armed while the request is in flight. Drop it below, and the parameter still registers (surviving the await is what it's for), but too late — the fetch has already resolved, and an abort on a settled controller cancels nothing.

Avoid:

  watch(id, async (v, _prev, onCleanup) => {
    const controller = new AbortController()
    await fetch(url, { signal: controller.signal })
    onCleanup(() => controller.abort()) // registers fine — but the fetch already resolved, so there's nothing left to abort
  })
Enter fullscreen mode Exit fullscreen mode

Prefer:

  watch(id, async (v, _prev, onCleanup) => {
    const controller = new AbortController()
    onCleanup(() => controller.abort()) // registered before the await, so the next change can abort this fetch mid-flight
    await fetch(url, { signal: controller.signal })
  })
Enter fullscreen mode Exit fullscreen mode
  • No appetite to own the registry — reach for a library; useFetch({ refetch: true }), or a TanStack query that forwards signal, is the same AbortController with the bookkeeping hidden.

Avoid:

  // hand-rolling abort + dedup + retry for a plain search box
  watch(term, async (t, _prev, onCleanup) => {
    const controller = new AbortController()
    onCleanup(() => controller.abort())
    // ...plus dedup keying and retry/backoff, all by hand...
    await fetch(`/api/search?q=${t}`, { signal: controller.signal })
  })
Enter fullscreen mode Exit fullscreen mode

Prefer:

  const { data } = useFetch(url, { refetch: true }).json() // abort-on-change, built in
Enter fullscreen mode Exit fullscreen mode

The three cases are three distinct fixes: co-locate in synchronous code, thread the parameter across async, or delegate the whole registry to a library that speaks AbortSignal.

The four names collapse to two ways into one registry, plus the object that does the aborting; 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

Top comments (1)

Collapse
 
merbayerp profile image
Mustafa ERBAY

This is an excellent explanation of the difference between onWatcherCleanup and the watcher-bound onCleanup parameter. The synchronous-registration boundary is easy to miss, and the before/after await examples make it very clear.

One distinction I would add is that aborting fetch does not necessarily cancel all server-side work. It stops the client request and prevents stale response handling, but the database query, upstream call, or background operation may continue unless cancellation is explicitly propagated through the server stack. So AbortController reliably addresses client-side correctness and resource lifetime, while eliminating backend work depends on the server implementation.

I would also double-check the claim that VueUse useFetch provides request deduplication “for free.” Its documented behavior covers aborting and reactive refetching, but general in-flight deduplication is usually associated with query-key and cache-oriented libraries such as TanStack Query.

Finally, the cleanupMap and activeWatcher explanation is very useful, though I would present those as details of Vue’s current implementation rather than part of the public API contract.

Overall, this is one of the clearest explanations I have seen of why cleanup registration position matters in asynchronous Vue watchers.