javascript / expert
Snippet
Async Task Cancellation via Custom Vue Effect Scope Disposables
Vue's effectScope encapsulates reactive subscriptions and side-effects. By linking an AbortController inside effectScope and registering an abort call onScopeDispose, asynchronous network operations cleanly cancel when the scope stops.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { ref, effectScope, onScopeDispose } from 'vue';export function useCancellableFetch(urlProvider) {const data = ref(null);const error = ref(null);const scope = effectScope();scope.run(() => {const controller = new AbortController();onScopeDispose(() => {controller.abort('Scope disposed');});const execute = async () => {try {const response = await fetch(urlProvider(), { signal: controller.signal });if (!response.ok) throw new Error(`HTTP ${response.status}`);data.value = await response.json();} catch (err) {if (err.name !== 'AbortError') error.value = err;}};execute();});return { data, error, stop: () => scope.stop() };}
vue
Breakdown
1
const scope = effectScope();
Creates an isolated reactive effect scope container to capture disposable effects.
2
onScopeDispose(() => { controller.abort('Scope disposed'); });
Registers a cleanup hook triggered automatically when scope.stop() is executed.
3
if (err.name !== 'AbortError') error.value = err;
Filters out intentional cancellation signals from actual runtime errors.