vize:croquis/cf/watcher-outside-setup
watch or watchEffect is called outside setup.
Default severity: Not emitted
Applies to: Analyzed component graph and the supported facts described below
Automatic fix: None; review related files and apply the repair
Options: No per-code options; supported CLI findings accept severity overrides
This is a published diagnostic contract without a current producer. The Bad/Good scenario below explains the risk and repair; no flag currently makes this code trigger.
Module-scope watchers are valid when their owner keeps and calls a stop handle or intentionally gives them application lifetime. This example requires component-owned lifetimes; the contract has no current producer.
Shared project files
Use these unchanged files in both Bad and Good. Install the imported packages in the project: Vue, plus vue-router or Pinia where shown. Follow any version-specific support note. The entry root makes the component relationship explicit.
main.ts
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');
index.html
<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><title>Contract scenario</title></head>
<body><div id="app"></div><script type="module" src="/main.ts"></script></body></html>
App.vue
<script setup lang="ts">
import Observer from './Observer.vue';
</script>
<template>
<Observer /><Observer />
</template>
Observer.vue
<script setup lang="ts">
import { useObserver } from './use-observer';
const { count, observed } = useObserver();
</script>
<template>
<button @click="count++">{{ count }}</button><p>{{ observed }}</p>
</template>
Bad
The watcher is created at module load, outside either Observer’s setup, and both instances share its refs. It is not automatically stopped when a particular Observer unmounts.
use-observer.ts
import { ref, watch } from 'vue';
const count = ref(0);
const observed = ref(0);
watch(count, next => { observed.value = next; });
export function useObserver() { return { count, observed }; }
Good
Each synchronous setup call creates its own refs and watcher inside useObserver. Vue associates that watcher with the calling component’s lifetime.
use-observer.ts
import { ref, watch } from 'vue';
export function useObserver() {
const count = ref(0);
const observed = ref(0);
watch(count, next => { observed.value = next; });
return { count, observed };
}
The Good files demonstrate the change described above; other diagnostics can still apply to the complete project.