New Jan 9, 2026

why does my vue code will cause a memory leak?

Libraries, Frameworks, etc. All from Newest questions tagged vue.js - Stack Overflow View why does my vue code will cause a memory leak? on stackoverflow.com

<script setup>
import { ref, onMounted, onBeforeUnmount, toRefs } from 'vue'

const props = defineProps({
  sessionUrl: { type: String, required: true },
  offerData: { type: Object, required: true }
})

const { sessionUrl, offerData } = toRefs(props)

const httpIntervalId = ref(null)
const fetchControllers = ref([])

const MAX_CONCURRENT = 3

const sendHttpRequest = async (candidates) => {
  if (fetchControllers.value.length >= MAX_CONCURRENT) return

  const controller = new AbortController()
  fetchControllers.value.push(controller)

  try {
    const res = await fetch(sessionUrl.value, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/trickle-ice-sdpfrag',
        'If-Match': '*'
      },
      body: generateSdpFragment(offerData.value, candidates),
      signal: controller.signal
    })

  } catch (err) {
    if (err.name === 'AbortError') {
    } else {
      console.error('fetch error', err)
    }
  } finally {
    const idx = fetchControllers.value.indexOf(controller)
    if (idx !== -1) fetchControllers.value.splice(idx, 1)
  }
}

const cancelHttpRequest = (msg) => {
  if (!fetchControllers.value || fetchControllers.value.length === 0) return

  const controllers = fetchControllers.value.slice()
  controllers.forEach((c) => {
    try { c.abort() } catch (e) { /* ignore */ }
  })

  fetchControllers.value = []
}

const generateSdpFragment = (offerData, candidates) => {
  return ''
}

onMounted(() => {
  if (httpIntervalId.value) {
    clearInterval(httpIntervalId.value)
    httpIntervalId.value = null
  }

  httpIntervalId.value = setInterval(() => {
    sendHttpRequest()
  }, 5000)
})

onBeforeUnmount(() => {
  if (httpIntervalId.value) {
    clearInterval(httpIntervalId.value)
    httpIntervalId.value = null
  }
  cancelHttpRequest()
})

defineExpose({ cancelHttpRequest })
</script>

I wrote this code to make an HTTP request in a VUE application, and I use AbortController to cancel the request. These AbortControllers will be put into a ref([]), but for some reason, my code causes a memory leak, and I don't know the reason.

If I assign controller = null in the finally section this issue can be fixed, but I do not know the reason.

What causes the memory leak?

Scroll to top