Erreurs d’exécution
Erreurs client
async_derived_orphan
Cannot create a `$derived(...)` with an `await` expression outside of an effect treeIl y a deux types de réactions dans Svelte — les $derived et les
$effect. Les dérivés peuvent être créés n’importe où, car ils sont
exécutés en différé et peuvent être nettoyés par le
ramasse-miettes si plus rien ne
leur fait référence. Les effets, en revanche, continuent d’être exécutés immédiatement dès qu’une de
leurs dépendances change, tant qu’ils n’ont pas été détruits.
Pour cette raison, les effets peuvent uniquement être créés au sein d’autres effets (ou d’effets racine, tels que celui qui est créé lorsque vous montez un composant pour la première fois), afin que Svelte sache quand les détruire.
Un tour de passe-passe se produit lorsqu’un dérivé contient une expression await : puisqu’attendre
jusqu’à ce qu’on lise {await getPromise()} pour appeler getPromise ferait arriver trop tard,
nous utilisons un effet pour plutôt l’appeler proactivement, prévenant Svelte lorsque la valeur est
rendue disponible. Mais puisque nous utilisons un effet, nous pouvons uniquement créer des dérivés
asynchrones au sein d’un autre effet.
bind_invalid_checkbox_value
Using `bind:value` together with a checkbox input is not allowed. Use `bind:checked` insteadbind_invalid_export
Component %component% has an export named `%key%` that a consumer component is trying to access using `bind:%key%`, which is disallowed. Instead, use `bind:this` (e.g. `<%name% bind:this={component} />`) and then access the property on the bound component instance (e.g. `component.%key%`)bind_not_bindable
A component is attempting to bind to a non-bindable property `%key%` belonging to %component% (i.e. `<%name% bind:%key%={...}>`). To mark a property as bindable: `let { %key% = $bindable() } = $props()`component_api_changed
Calling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5See the migration guide for more information.
component_api_invalid_new
Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working.See the migration guide for more information.
derived_references_self
A derived value cannot reference itself recursivelyeach_key_duplicate
Keyed each block has duplicate key at indexes %a% and %b%Keyed each block has duplicate key `%value%` at indexes %a% and %b%effect_in_teardown
`%rune%` cannot be used inside an effect cleanup functioneffect_in_unowned_derived
Effect cannot be created inside a `$derived` value that was not itself created inside an effecteffect_orphan
`%rune%` can only be used inside an effect (e.g. during component initialisation)effect_pending_outside_reaction
`$effect.pending()` can only be called inside an effect or derivedeffect_update_depth_exceeded
Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of stateSi un effet met à jour un ou plusieurs états dont il dépend, il sera ré-exécuté, potentiellement en boucle :
let let count: numbercount = function $state<0>(initial: 0): 0 (+1 overload)
namespace $state
$state(0);
function $effect(fn: () => void | (() => void)): void
namespace $effect
Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values.
The timing of the execution is after the DOM has been updated.
Example:
$effect(() => console.log('The count is now ' + count));
If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
Does not run during server-side rendering.
$effect(() => {
// ceci lit et écrit `count`,
// provoquant une boucle infinie
let count: numbercount += 1;
});(Svelte intervient avant que ceci ne fasse planter votre onglet de navigateur.)
La même chose est vraie pour les mutations de tableau, puisqu’elles lisent et écrivent le tableau :
let let array: string[]array = function $state<string[]>(initial: string[]): string[] (+1 overload)
namespace $state
$state(['hello']);
function $effect(fn: () => void | (() => void)): void
namespace $effect
Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values.
The timing of the execution is after the DOM has been updated.
Example:
$effect(() => console.log('The count is now ' + count));
If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
Does not run during server-side rendering.
$effect(() => {
let array: string[]array.Array<string>.push(...items: string[]): numberAppends new elements to the end of an array, and returns the new length of the array.
push('goodbye');
});Notez que c’est acceptable pour un effet de se ré-exécuter lui-même tant qu’il “converge” :
function $effect(fn: () => void | (() => void)): void
namespace $effect
Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values.
The timing of the execution is after the DOM has been updated.
Example:
$effect(() => console.log('The count is now ' + count));
If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
Does not run during server-side rendering.
$effect(() => {
// ceci est acceptable, car le tri d'un tableau déjà trié
// ne va pas déclencher une mutation
let array: string[]array.Array<string>.sort(compareFn?: ((a: string, b: string) => number) | undefined): string[]Sorts an array in place.
This method mutates the array and returns a reference to the same array.
sort();
});Souvent lorsque l’on tombe sur ce problème, la valeur en question ne devrait pas être un état (par
exemple, si vous ajoutez des éléments dans un tableau de logs dans un effet, transformez logs en
un tableau normal plutôt qu’un $state([])). Dans les rares cas où vous avez vraiment besoin
de mettre à jour un état dans un effet — ce que vous devriez
éviter — vous pouvez lire l’état avec untrack
pour éviter de l’ajouter en tant que dépendance.
experimental_async_fork
Cannot use `fork(...)` unless the `experimental.async` compiler option is `true`flush_sync_in_effect
Cannot use `flushSync` inside an effectLa fonction flushSync() peut être utilisée pour nettoyer tout effet en attente de manière
synchrone. Elle ne peut pas être utilisée si des effets sont en train d’être nettoyés — autrement
dit, vous pouvez l’appeler après un changement d’état mais pas au sein d’un effet.
Cette restriction s’applique uniquement lorsque vous utilisez l’option experimental.async, qui
sera active par défaut en Svelte 6.
fork_discarded
Cannot commit a fork that was already discardedfork_timing
Cannot create a fork inside an effect or when state changes are pendingget_abort_signal_outside_reaction
`getAbortSignal()` can only be called inside an effect or derivedhydration_failed
Failed to hydrate the applicationinvalid_snippet
Could not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`lifecycle_legacy_only
`%name%(...)` cannot be used in runes modeprops_invalid_value
Cannot do `bind:%key%={undefined}` when `%key%` has a fallback valueprops_rest_readonly
Rest element properties of `$props()` such as `%property%` are readonlyrune_outside_svelte
The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` filesset_context_after_init
`setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expressionThis restriction only applies when using the experimental.async option, which will be active by default in Svelte 6.
state_descriptors_fixed
Property descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.state_prototype_fixed
Cannot set prototype of `$state` objectstate_unsafe_mutation
Updating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`Cette erreur se produit lorsqu’un état est mis à jour pendant l’évaluation d’un $derived. Vous
pourriez la rencontrer alors que vous essayez de “dériver” deux morceaux d’état en une seule fois :
<script>
let count = $state(0);
let even = $state(true);
let odd = $derived.by(() => {
even = count % 2 === 0;
return !even;
});
</script>
<button onclick={() => count++}>{count}</button>
<p>{count} est pair : {even}</p>
<p>{count} est impair : {odd}</p>Ceci est interdit car cela introduit de l’instabilité : si <p>{count} est pair : {even}</p> est
mis à jour avant que odd ne soit recalculé, even sera périmé. Dans la plupart des cas, la
solution est de tout dériver :
let let even: booleaneven = function $derived<boolean>(expression: boolean): boolean
namespace $derived
Declares derived state, i.e. one that depends on other state variables.
The expression inside $derived(...) should be free of side-effects.
Example:
let double = $derived(count * 2);
$derived(let count: numbercount % 2 === 0);
let let odd: booleanodd = function $derived<boolean>(expression: boolean): boolean
namespace $derived
Declares derived state, i.e. one that depends on other state variables.
The expression inside $derived(...) should be free of side-effects.
Example:
let double = $derived(count * 2);
$derived(!let even: booleaneven);Si les effets de bord sont inévitable, utilisez plutôt $effect.
svelte_boundary_reset_onerror
A `<svelte:boundary>` `reset` function cannot be called while an error is still being handledSi une balise <svelte:boundary> a une fonction onerror, elle ne doit pas
appeler la fonction reset de manière synchrone, puisque la frontière est toujours dans un état
d’erreur. reset() est typiquement appelée plus tard, une fois que l’erreur a été résolue.
S’il est possible de résoudre l’erreur dans le callback onerror, vous devez au moins attendre que
la frontière se stabilise avant d’appeler reset(), par exemple en utilisant
tick :
<svelte:boundary onerror={async (error, reset) => {
fixTheError();
await tick();
reset();
}}>
</svelte:boundary>Erreurs serveur
await_invalid
Encountered asynchronous work while rendering synchronously.Vous (ou le framework que vous utilisez) avez appelé render(...) avec un
composant contenant une expression await. Vous devez soit await le résultat de render ou
entourer le await (ou le composant le contenant) dans un <svelte:boundary>
ayant un snippet pending.
html_deprecated
The `html` property of server render results has been deprecated. Use `body` instead.lifecycle_function_unavailable
`%name%(...)` is not available on the serverCertaines méthodes comme mount ne peuvent pas être invoquées lorsqu’exécutées dans un contexte
serveur. Évitez de les appeler immédiatement, c’est-à-dire pas pendant le rendu.
Erreurs client et serveur
invalid_default_snippet
Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet insteadCette erreur serait levée dans une situation comme celle-ci :
<List {items} let:entry>
<span>{entry}</span>
</List><script>
let { items, children } = $props();
</script>
<ul>
{#each items as item}
<li>{@render children(item)}</li>
{/each}
</ul><script lang="ts">
let { items, children } = $props();
</script>
<ul>
{#each items as item}
<li>{@render children(item)}</li>
{/each}
</ul>Ici, List.svelte utilise {@render children(item)}, ce qui signifie qu’elle attend
Parent.svelte pour utiliser des snippets. Mais en réalité Parent.svelte utilise la directive
let:, qui est dépréciée. Cette combinaison d’APIs est incompatible, d’où l’erreur.
invalid_snippet_arguments
A snippet function was passed invalid arguments. Snippets should only be instantiated via `{@render ...}`lifecycle_outside_component
`%name%(...)` can only be used during component initialisationCertaines méthodes de cycle de vie ne peuvent être utilisées que lors de l’initialisation d’un composant. Pour corriger ça, assurez-vous d’invoquer la méthode à la racine du script de l’instance de votre composant.
<script>
import { onMount } from 'svelte';
function handleClick() {
// ceci est mauvais
onMount(() => {})
}
// ceci est bon
onMount(() => {})
</script>
<button onclick={handleClick}>cliquez moi</button>missing_context
Context was not set in a parent componentL’utilitaire createContext() renvoie une paire de fonctions [get, set].
get jette une erreur si set n’a pas été utilisée pour définir le contexte dans un composant
parent.
snippet_without_render_tag
Attempted to render a snippet without a `{@render}` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change `{snippet}` to `{@render snippet()}`.Un composant qui jette cette erreur va ressembler à ça (children n’est pas rendu)...
<script>
let { children } = $props();
</script>
{children}... ou à ça (un composant parent fournit un snippet là où une valeur non-snippet est attendue) :
<ChildComponent>
{#snippet label()}
<span>Salut !</span>
{/snippet}
</ChildComponent><script>
let { label } = $props();
</script>
<!-- Ce composant n'attend pas un snippet, mais le parent en fournit un -->
<p>{label}</p><script lang="ts">
let { label } = $props();
</script>
<!-- Ce composant n'attend pas un snippet, mais le parent en fournit un -->
<p>{label}</p>store_invalid_shape
`%name%` is not a store with a `subscribe` methodsvelte_element_invalid_this_value
The `this` prop on `<svelte:element>` must be a string, if definedModifier cette page sur Github llms.txt