svelte: "Updating state inside a derived or logic block expression is forbidden" inside { @html function_that_modifies_state() }

Describe the bug

This fails: https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAA41RsW7cMAz9FYbNYCOG3dm9HGp0aIdkc7tUHXQ2hRMqU4JEJw0M_3shX-8uaDp0IvhIPr5HLmiso4Tt9wVZT4QtdiFghfIScpKeyAlhhcnPccjILg3RBtkrVmKn4KNAHzVn9EBgop9AYd1csfrEoTBPOBIY_MwC93CbRAsV78sPis-1dMWXkXULCj93fd996hSuZe5SvGuuEnh5Zw2kemS95urulZaD5bFN0OwVL401q2KscPKjNZZGbCXOtFYX29fB_3T_R_GySc679MFRUa45DdGHVJyNmZkHsZ5BLjt6_6V_fChKWDZPYg0UN6mOrC-QkqaBbxRfgH4F4mSfCHygqDeqIuiYCCYdf47-meHZyhE0OC_gDRgfp9npVIJliKQd6BCcHbR4fsXeHwkipdkJ2ASDHo401uf6pgbuQeEu7BXC3enMdaTg9ECdc4XCXmEFCr8qLOEutza590SxnkIkmSPDRpeR9e8PfjzK5P5xm_Xtu36svwGcihQnsQIAAA==

My workaround is to not call the function from {@html }, but rather use $effect to calculate the value: H4sIAAAAAAAAA41SwY7TMBD9lWHYQ6KNEs6lrYg4wAFugQvm4CZj1cIZW_Zkl1WUf0dOaLtSOXCy_GbmzXvPntFYRwl3P2ZkPRLusA0BK5SXkC_piZwQVpj8FPuM7FMfbZCjYiV2DD4KdFFzRk8EJvoRFNbNDas3DoV5wpFA7ycWOMBDEi1UvCvfK77U0g2fB9Y7UPip7br2Y6twKXOX4n1zk8DzW2sg1QPrJVf3r7ScLA

Offending component code:

<script>
	let {s = $bindable()} = $props();

	function transcribeToHTML() {
		if (!s.rna) {
			// Very expensive operation (parse markdown with a lot of formulas) in real applicaton
			// The result is cached.
			s.rna = "<p>" + s.dna.replaceAll("T", "U") + "</p>"
		}
		return s.rna
	}
</script>

{@html transcribeToHTML()}

which is included inside {#if } in the parent.

I’m not sure if this is a bug or I misunderstood something.

Reproduction

run in playground

Logs

No response

System Info

.268, playground

Severity

annoyance

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 21 (14 by maintainers)

Most upvoted comments

This patterns Just Works ™️ in Svelte 4. Keeping it working would make the transition easier.

It will continue to work in non-runes mode. What Svelte 4 was doing was the source of so many issues, so it’s rightfully an error now – having it as a warning will just let people ignore it, which in turn leads to more issues further on down the line.

@trueadm Please consider the other direction - allow mutations in as many places as possible, and then implement a compile time warning drawing the users attention to the fact that they are pointing a shotgun at their foot.

This patterns Just Works ™️ in Svelte 4. Keeping it working would make the transition easier.

It can’t be a compile time check because we could have no visibility inside the function. Mutating inside the template is rarely useful and the same “effect” could be achieved in better ways.