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:

  1. The lifecycle hook is not registered.
  2. 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.

Note: Not applied for top-level await inside <script setup> because Vue applies automatic instance restore when compiling <script setup>.

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();
  }
}
</script>

<!-- 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

Was this documentation helpful?