sveltejs/svelte · error · Error

lifecycle_outside_component

lifecycle_outside_component

Error message

lifecycle_outside_component
`${name}(...)` can only be used during component initialisation
https://svelte.dev/e/lifecycle_outside_component

What it means

Svelte lifecycle functions (`onMount`, `onDestroy`, `beforeUpdate`, `afterUpdate`, and rune-based equivalents) only work during component initialization — the synchronous setup phase when the component function runs. Calling them later throws because there is no active component context. The `%name%` identifies which lifecycle function was misused.

Source

Thrown at packages/svelte/src/internal/shared/errors.js:84

	} else {
		throw new Error(`https://svelte.dev/e/invariant_violation`);
	}
}

/**
 * `%name%(...)` can only be used during component initialisation
 * @param {string} name
 * @returns {never}
 */
export function lifecycle_outside_component(name) {
	if (DEV) {
		const error = new Error(`lifecycle_outside_component\n\`${name}(...)\` can only be used during component initialisation\nhttps://svelte.dev/e/lifecycle_outside_component`);

		error.name = 'Svelte error';

		throw error;
	} else {
		throw new Error(`https://svelte.dev/e/lifecycle_outside_component`);
	}
}

/**
 * Context was not set in a parent component
 * @returns {never}
 */
export function missing_context() {
	if (DEV) {
		const error = new Error(`missing_context\nContext was not set in a parent component\nhttps://svelte.dev/e/missing_context`);

		error.name = 'Svelte error';

		throw error;
	} else {
		throw new Error(`https://svelte.dev/e/missing_context`);
	}
}

View on GitHub (pinned to 20b341f100)

Solutions

  1. Register lifecycle functions synchronously at the top of component init, before any `await`.
  2. Do async work inside the lifecycle callback: `onMount(async () => { await ... })`.
  3. Move lifecycle registration out of event handlers and timeouts into the component body.

Example fix

// before
let data;
async function init() {
	await load();
	onMount(() => console.log('mounted')); // throws: past await, no component context
}
// after
onMount(async () => {
	await load();
	console.log('mounted');
});
Defensive patterns

Strategy: validation

Prevention

When it happens

Trigger: Calling `onMount(...)` inside an `async` function after an `await` (context is lost across the boundary); calling a lifecycle in an event handler or `setTimeout` callback; calling it from a plain `.js`/`.ts` module outside any component.

Common situations: Top-level `await` in component init that pushes lifecycle calls past the await; calling `onMount` from a utility not always invoked during init; refactoring init code into async helpers.

Related errors


AI-assisted analysis of sveltejs/svelte@20b341f100 (2026-08-12). Data as JSON: /api/errors/794baeee2ec77f1a. Report an issue: GitHub.