Skip to content

Effect wrapped in $effect.root cannot be used in teardown #15245

@thes01

Description

@thes01

Describe the bug

I thought $effect.root could be used as a "safe environment" for housing effects when you do the care with cleaning up.
However, if that happens to be in onDestroy, then any effect will throw a runtime error regardless it's wrapped in an effect root or not.

To illustrate the use case let's say I have the following function:

export async function get_when_ready(
	getter,  // getter to a reactive value
	predicate,
) {
	const { promise, resolve } = Promise.withResolvers();
	
	const cleanup = $effect.root(() => {
		$effect.pre(() => {
			const value = getter();
			if (predicate(value)) {
				resolve(value);
			}
		});
	});

	// clean the $effect.root after the promise has resolved/rejected
	promise.catch(() => {}).finally(cleanup);

	return promise;
}

Firstly, I don't know if the function is implemented correctly, if not, I'll be glad for any hints. I haven't seen it implemented elsewhere, but also I haven't looked thoroughly.

Given the above utility function and an API that calls it internally, I ran into a situation, where I called the API in the onDestroy of a component.

Reproduction

The REPL is here: https://svelte.dev/playground/d96d1b9b36264a6a83685b0e99552969?version=5.19.9

Note that it doesn't make much sense for the API (MyContext.delete_feature) to call the utility function there, but I hope it's sufficient to illustrate the problem.

I wonder if it's a false positive error or there's some underlying issue there.

System Info

System:
    OS: Windows 11 10.0.26100
    CPU: (16) x64 AMD Ryzen 7 PRO 6850U with Radeon Graphics
    Memory: 5.61 GB / 14.76 GB
  Binaries:
    Node: 22.9.0 - ~\AppData\Local\fnm_multishells\5844_1739017727831\node.EXE
    Yarn: 4.6.0 - ~\AppData\Local\fnm_multishells\5844_1739017727831\yarn.CMD
    npm: 10.9.0 - ~\AppData\Local\fnm_multishells\5844_1739017727831\npm.CMD
    bun: 1.2.1 - E:\designer\node_modules\.bin\bun.CMD
  Browsers:
    Edge: Chromium (131.0.2903.146)
    Internet Explorer: 11.0.26100.1882

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions