Lifecycle hooks and watchers should not be registered after await
in an async function
- VUE_MISUSED_API_AFTER_AWAIT
- Error
- Medium
- vue
This rule applies when lifecycle hook or watcher registration APIs are called after await
in an async function.
Those APIs should be called when there is an active Vue component instance to be associated with. However, the active instance is lost after await
, which causes the following problems:
- The lifecycle hook is not registered.
- The watcher is not removed automatically when the instance is unmounted. Note that you can use the stop handle returned by the registration API to manually remove the watcher.
Noncompliant Code Example
View with compliant examples side by side<!-- Example 1 -->
<script>
import { onMounted } from 'vue';
export default {
async setup() {
await doSomething();
onMounted(() => console.log("mounted")); // VUE_MISUSED_API_AFTER_AWAIT alarm
}
}
</script>
<!-- Example 2 -->
<script>
import { watch } from 'vue';
export default {
async setup() {
const count = ref(0);
await doSomething();
watch(count, () => console.log("count: " + count.value)); // VUE_MISUSED_API_AFTER_AWAIT alarm
}
}
</script>
Compliant Code Example
View with noncompliant examples side by side<!-- Example 1 -->
<script>
import { onMounted } from 'vue';
export default {
async setup() {
onMounted(() => console.log("mounted"));
await doSomething();
}
}
<!-- Example 2 -->
<script>
import { watch } from 'vue';
export default {
async setup() {
const count = ref(0);
watch(count, () => console.log("count: " + count.value));
await doSomething();
}
}
</script>
Version
This rule was introduced in DeepScan 1.42.0.
See
[Vue warn]: onMounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.