Subscribe on changes!

watchEffect BUG

avatar
Oct 16th 2023

Vue version

3.3.4

Link to minimal reproduction

https://cn.vuejs.org/api/reactivity-core.html#watcheffect

Steps to reproduce

import { ref, watchEffect } from 'vue' const r = ref(0) function sleep(time){ return new Promise((resolve)=>{ setTimeout(() => { resolve() }, time); }) } watchEffect(async ()=>{ await sleep(500) console.log('watch1',r.value) }) setTimeout(() => { r.value = 2 }, 3000);

What is expected?

Should listen for changes in r

What is actually happening?

Only printed: watch1 0

System Info

No response

Any additional comments?

I changed the code: import { ref, watchEffect } from 'vue' const r = ref(0) function sleep(time){ return new Promise((resolve)=>{ setTimeout(() => { resolve() }, time); }) } watchEffect(async ()=>{ console.log('watch1',r.value) await sleep(500) }) setTimeout(() => { r.value = 2 }, 3000); Printed: watch1 0 watch1 2

avatar
Oct 16th 2023

watchEffect cannot be used to watch data within asynchronous queues. If you specifically need to watch a variable, you should use watch. If you use watchEffect, you need to access the variable before entering the asynchronous queue.