How to cancel requests in Vue
Canceling HTTP requests in Vue prevents unnecessary network usage, avoids race conditions, and improves application performance when components unmount or routes change. As the creator of CoreUI with extensive Vue.js experience since its early versions, I’ve implemented request cancellation in numerous data-driven applications and component libraries. From my expertise, the most effective approach is using AbortController with the Composition API to automatically cancel requests on component cleanup. This technique ensures clean component lifecycle management and prevents memory leaks from pending requests.
Use AbortController with Vue’s Composition API to cancel requests automatically on component unmount.
import { ref, onUnmounted } from 'vue'
export default {
setup() {
const data = ref(null)
const controller = new AbortController()
const fetchData = async () => {
try {
const response = await fetch('/api/data', {
signal: controller.signal
})
data.value = await response.json()
} catch (error) {
if (error.name !== 'AbortError') {
console.error('Fetch error:', error)
}
}
}
onUnmounted(() => {
controller.abort()
})
return { data, fetchData }
}
}
Here new AbortController() creates a controller for managing request cancellation, and controller.signal is passed to the fetch request. The onUnmounted() lifecycle hook calls controller.abort() to cancel any pending requests when the component is destroyed. The catch block checks for ‘AbortError’ to handle cancelled requests gracefully. This pattern prevents state updates on unmounted components and eliminates memory leaks from pending HTTP requests.
Best Practice Note:
This is the same approach we use in CoreUI Vue components for robust data fetching and component cleanup in single-page applications. Always cancel pending requests in onUnmounted to prevent errors from updating destroyed components and to maintain optimal application performance.



