LL3006
LL3006
NNuxt
Created by LL3006 on 4/6/2025 in #❓・help
callOnce loses Nuxt context after first await
I have a setup like this, where quote is a pinia store and it works
await callOnce(async () => {
await quote.loadQuote(); // This calls useNuxtApp() somewhere
});
await callOnce(async () => {
await quote.loadQuote(); // This calls useNuxtApp() somewhere
});
However as soon as I await for anything else inside callOnce, like e.g.
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

await callOnce(async () => {
await sleep(100);
await quote.loadQuote(); // This calls useNuxtApp() somewhere
});
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

await callOnce(async () => {
await sleep(100);
await quote.loadQuote(); // This calls useNuxtApp() somewhere
});
Suddenly, the page errors out with a
[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables. at useNuxtApp (/home/ll3006/sample-project/node_modules/nuxt/dist/app/nuxt.js:248:13) at useAPI (/home/ll3006/sample-project/composables/useAPI.ts:3:56) at Proxy.loadQuote (/home/ll3006/sample-project/stores/quote.ts:7:49) at Proxy.wrappedAction (/home/ll3006/sample-project/node_modules/pinia/dist/pinia.mjs:1379:26) at /home/ll3006/sample-project/app.js:17:19) at async callOnce (/home/ll3006/sample-project/node_modules/nuxt/dist/app/composables/once.js:25:3) at async setup (/home/ll3006/sample-project/app.js:18:25)
Which looks to me like loadQuote doesn't work as it can't access useNuxtApp anymore. useNuxtApp is ultimately used to load the api endpoint from the runtimeConfig, through a custom $fetch-like $api plugin. Using $fetch and manually hardcoding the endpoit works as expected. The problem therefore lies in the fact that only the first await seems to receive the nuxt context. Why does this happen? What causes loadQuote to lose access to the nuxt context? Can I work around this?
10 replies