VUE
Cancel stale async work in watchers with onWatcherCleanup()
composables/useUser.ts
typescriptimport { watch, onWatcherCleanup } from 'vue'
watch(id, (newId) => {
const controller = new AbortController()
fetch(`/api/users/${newId}`, { signal: controller.signal })
.then((r) => r.json())
.then((data) => { /* apply */ })
onWatcherCleanup(() => controller.abort())
})Registered inside the watcher callback, `onWatcherCleanup` runs before the next invocation and on stop. It removes the manual "is this response still relevant?" flag most people hand-roll, and prevents a slow earlier request from overwriting the result of a newer one — the classic race in search-as-you-type. Pair it with `AbortController` for fetch, or use it to clear timers and subscriptions. Available in Vue 3.5+.
watchersasyncreactivityvue3.5