`watchEffect` within `effectScope` is removed when component is unmounted
Vue version
edge
Link to minimal reproduction
Steps to reproduce
- Click the "negate button" -> see multiple logs
- untick the checkbox and tick it again (triggers unmount + mount of component)
- Click the negate button again -> see only one log
What is expected?
watchEffect should trigger because it's inside of a detached effectScope
What is actually happening?
watchEffect isn't run anymore after the wrapping component unmounts
System Info
na
Any additional comments?
let scope;
let store;
export function useCustomStore() {
- if (store) return store; // comment this line will works fine.
scope = scope || effectScope(true);
store = scope.run(() => {
const flag = ref(false);
+ The root cause is that an unmounted instance is cached in `watchEffect`.
+ When the component is re-mount, we create a new instance of the component.
+ But because `if (store) return store;` causes `watchEffect` not to be re-executed,
+ so its internal instance is the component instance that has been unmounted.
watchEffect(() => {
console.log('watchEffect flag', flag.value)
})
watch(flag, () => {
console.log('watch flag', flag.value)
})
return ({
flag,
});
});
return store
}
But the watchEffect should be attached to the effectScope like a regular watch The return is intentional to simulate a store
@posva Actuality, the instance in the regular watch callback is also incorrect and is unmounted. It can execute because we don't determine if the instance is unmounted like watchEffect does.
watch(flag, () => {
console.log('watch flag', flag.value)
})