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.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to dynamically add, remove, and toggle CSS classes in React.js
How to dynamically add, remove, and toggle CSS classes in React.js

How to disable a button in JavaScript
How to disable a button in JavaScript

What Does javascript:void(0) Mean?
What Does javascript:void(0) Mean?

How to show or hide elements in React? A Step-by-Step Guide.
How to show or hide elements in React? A Step-by-Step Guide.

Answers by CoreUI Core Team