Skip to content

vue-setup-after-await ​

A lifecycle hook, watcher, computed, provide/inject or similar Vue API called after an await in a function.

Why: these APIs attach to the component being set up, and Vue only knows which one that is until the function's first await. After it, a hook registers nowhere and never runs, a watcher is never stopped when the component goes away, and inject finds nothing. Guide: Vue.

ts
import { onUnmounted, shallowRef } from "vue";

async function connect(url: string): Promise<WebSocket> {
  return new WebSocket(url);
}

export async function useChat(url: string) {
  const socket = await connect(url);
  const messages = shallowRef<readonly string[]>([]);
  onUnmounted(() => socket.close());
  return messages;
}

✅ Accepted: register everything first, start the async work afterwards

✓ Accepted0 diagnostics
ts
import { onMounted, onUnmounted, shallowRef } from "vue";

async function connect(url: string): Promise<WebSocket> {
  return new WebSocket(url);
}

export function useChat(url: string) {
  const messages = shallowRef<readonly string[]>([]);
  const socket = shallowRef<WebSocket>();
  onMounted(async () => {
    socket.value = await connect(url);
  });
  onUnmounted(() => socket.value?.close());
  return messages;
}

A top-level await in <script setup> is fine: Vue's compiler restores the component after it. That only works there, not in composables or other async functions.

The APIs it checks: onMounted and the other lifecycle hooks, onScopeDispose, watch, watchEffect (and its Post/Sync forms), computed, provide, inject, useSlots, useAttrs, useTemplateRef, useId, useModel, getCurrentInstance, and vue-router's useRoute/useRouter.

What the rule can't see: these APIs called from another function that you call after the await (await load(); registerHooks()).

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra