The Problem
Pinia stores require an active Vue app instance to work. Calling useStore() outside a setup() function (in axios interceptors, utility functions, or Web Workers) fails because there is no current component instance.
Symptoms
- Error: "getActivePinia was called with no active Pinia"
- Store actions return undefined when called from API interceptors
- Stores work in components but not in standalone JavaScript files
- Pinia devtools does not show actions triggered outside components
Real Error Message
[Pinia]: "getActivePinia()" was called but there was no active Pinia.
Are you trying to use a store before calling "app.use(pinia)"?Common Scenario: Axios Interceptor
```javascript // api.js - WRONG import { useAuthStore } from '@/stores/auth';
const api = axios.create({ baseURL: '/api' });
api.interceptors.response.use( response => response, error => { if (error.response?.status === 401) { const authStore = useAuthStore(); // FAILS: no active Pinia! authStore.logout(); } return Promise.reject(error); } ); ```
How to Fix It
Fix 1: Pass Store as Parameter
```javascript // api.js export function setupInterceptors(authStore) { api.interceptors.response.use( response => response, error => { if (error.response?.status === 401) { authStore.logout(); // Works: store passed from component } return Promise.reject(error); } ); }
// In your main component or main.js import { useAuthStore } from '@/stores/auth'; import { setupInterceptors } from './api';
const authStore = useAuthStore(); setupInterceptors(authStore); ```
Fix 2: Use Pinia Instance Directly
```javascript // stores/index.js import { createPinia } from 'pinia';
export const pinia = createPinia();
// api.js import { pinia } from '@/stores'; import { useAuthStore } from '@/stores/auth';
api.interceptors.response.use( response => response, error => { if (error.response?.status === 401) { const authStore = useAuthStore(pinia); // Pass pinia instance authStore.logout(); } return Promise.reject(error); } ); ```
Fix 3: Initialize in main.js After Pinia
```javascript // main.js import { createApp } from 'vue'; import { createPinia } from 'pinia'; import App from './App.vue'; import { setupApiInterceptors } from './api';
const app = createApp(App); const pinia = createPinia();
app.use(pinia); app.mount('#app');
// Now Pinia is active, safe to use stores setupApiInterceptors(); ```
```javascript // api.js import { useAuthStore } from '@/stores/auth';
export function setupApiInterceptors() { api.interceptors.response.use( response => response, error => { if (error.response?.status === 401) { const authStore = useAuthStore(); // Now works: Pinia is active authStore.logout(); } return Promise.reject(error); } ); } ```
The key is calling setupApiInterceptors() AFTER app.use(pinia) and app.mount().