Vue · Senior · Question 7 of 75

What goes wrong when a lifecycle hook is registered after await in a plain setup() function?

export default {
  async setup() {
    const data = await load();
    onMounted(() => init(data)); // problem
  },
};

Explanation

Hooks, watch and inject rely on the active instance, which is only set during synchronous setup. Register them before the first await, or use <script setup>, whose compiler preserves the context.

Further reading

Problem with a question

Vue · Senior · question 7

Test yourself

Take the Vue · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz