vuejs / router

🚦 The official router for Vue.js

Home Page:https://router.vuejs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Promise function in async setup still execute when switch router

minhtien020900 opened this issue · comments

Reproduction

https://stackblitz.com/edit/vitejs-vite-zjpnie?file=src%2Fcomponents%2FHome.vue

Steps to reproduce the bug

  1. Step1: From page home, switch to /blog
  2. Step2: When page blog show loading, back to home
  3. Step3: Wait a few seconds, router will push '/about'

Expected behavior

  1. delay() function will be stopped as soon as when switch router
  2. Router not push to /about

Actual behavior

  1. delay() still executes even though the router has changed.
  2. Router is redirected to /about when current router is /home.

Thanks for the great reproduction! The behavior you are seeing isn't related to the router, it's just how things work with Suspense (and in JS in general). The watcher being immediate, executes even though the component never manages to mount (it doesn't even unmount). The solution is to move the watcher within an onMounted() to ensure this only runs if the component ever mounts