Erreurs d’exécution
Erreurs client
async_derived_orphan
Cannot create a `$derived(...)` with an `await` expression outside of an effect tree
Il 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` instead
bind_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 5
See 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 recursively
each_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 function
effect_in_unowned_derived
Effect cannot be created inside a `$derived` value that was not itself created inside an effect
effect_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 derived
effect_update_depth_exceeded
Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state
Si un effet met à jour un ou plusieurs états dont il dépend, il sera ré-exécuté, potentiellement en boucle :
let let count: number
count = 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: number
count += 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[]): number
Appends 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.
flush_sync_in_effect
Cannot use `flushSync` inside an effect
La 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.
get_abort_signal_outside_reaction
`getAbortSignal()` can only be called inside an effect or derived
hydration_failed
Failed to hydrate the application
invalid_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 mode
props_invalid_value
Cannot do `bind:%key%={undefined}` when `%key%` has a fallback value
props_rest_readonly
Rest element properties of `$props()` such as `%property%` are readonly
rune_outside_svelte
The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` files
set_context_after_init
`setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression
This 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` object
state_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: boolean
even = 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: number
count % 2 === 0);
let let odd: boolean
odd = 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: boolean
even);
Si les effets de bord sont inévitable, utilisez plutôt $effect
.
Erreurs serveur
lifecycle_function_unavailable
`%name%(...)` is not available on the server
Certaines 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
await_outside_boundary
Cannot await outside a `<svelte:boundary>` with a `pending` snippet
Le mot-clé await
peut uniquement apparaître des expressions $derived(...)
, des expressions de
template, ou à la racine du block <script>
d’un composant, s’il celui-ci se trouve dans un bloc
<svelte:boundary>
ayant un snippet pending
:
<svelte:boundary>
<p>{await getData()}</p>
{#snippet pending()}
<p>loading...</p>
{/snippet}
</svelte:boundary>
Cette restriction sera peut-être levée dans une version future de Svelte.
invalid_default_snippet
Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead
Cette 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 initialisation
Certaines 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>
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` method
svelte_element_invalid_this_value
The `this` prop on `<svelte:element>` must be a string, if defined
Modifier cette page sur Github llms.txt