svelte: Uncaught (in promise) TypeError: Cannot read property 'removeChild' of null

@jycouet @sudomaxime @torgebauer @orgertot @shedali @clineamb @kilianso if you could kindly post the following about your issues, so that we could better look into it:

  • Reproduction of the issue, github link / svelte repl (https://svelte.dev/repl) (Preferrable)
  • Svelte version you are using (Run yarn why svelte or npm list svelte)

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 9
  • Comments: 37 (7 by maintainers)

Commits related to this issue

Most upvoted comments

Just in case it’s useful to anyone else, here’s what specifically caused this issue for me and how I solved it:

My code:

{#each headers as header}
      <th on:click="{() => sortTable(header.key)}">
          {#if searchParams.sort === header.key && searchParams.order === 'asc'}
             <span><span style="height: 10px;" class="iconify" data-icon="fa:angle-up" data-inline="false"></span></span>
          {:else if searchParams.sort === header.key && searchParams.order === 'desc'}
             <span><span style="height: 10px;" class="iconify" data-icon="fa:angle-down" data-inline="false"></span></span>
          {/if}
          {header.name}
      </th>
{/each}

Basically, I have a sortable table where I wanted to place an icon next to the header of the column being sorted. I’m using Iconify icons and inserting them using <span> tags, but when the icons are actually loaded, the <span>s get converted to <svg>s. So, when I clicked the header to change the sort direction from ascending to descending, the <span> tag was no longer there for Svelte to remove. My solution above to to wrap an additional span around each element, so that that element can be located and targeted for removal.

This seems to be a regression bug. Fixed here: https://github.com/sveltejs/svelte/issues/2086#issuecomment-490989491 Broken again here: https://github.com/sveltejs/svelte/commit/6d16e9260642b1fcc70fa4a24be9fd49985112d1 Seems like this got caught in a revert even though it wasn’t related.

export function detach(node: Node) {
	if (is_hydrating) {
		nodes_to_detach.add(node);
	} else if (node.parentNode) {
		node.parentNode.removeChild(node);
	}
}

I’m using maplibre-gl and trying to make markers utilize slots for their HTMLElement property, but when cleaning up the marker it removes the element before Svelte does and Svelte gets confused.

Best solution would be just to return the original fix.

export function detach(node: Node) {
	if (node.parentNode) {
		node.parentNode.removeChild(node);
	}
}

Hello! I’d like to just bump this issue a bit and perhaps (hopefully) increase the urgency for a solution.

We’re seeing a lot of issues with users using Google Translate. Some cases we’ve solved by simply adding “notranslate” classes to affected components, but we’d really like to avoid spraying that all over our app.

If you want to see it in action, you can reproduce one case like this:

Since this is a long running issue, with multiple issues opened for 3 years, I thought that maybe I did something wrong in my Svelte code. And I don’t really want to patch the Svelte code. I tried to add multiple span or div to wrap various items like icons, nothing works. And I finally identified the root cause was a DOM.remove() I’m using to manage a list and front-run the Svelte mechanism to dismiss an element. Because on a table it is easier to control like that the contents and controlling out the animation.

It was like that :

{#each el as elts, i}
    <div id="domRemoved"}
         ...
    </div>
{/each}

And the fix is :

{#each el as elts, i}
    <div>
        <div id="domRemoved"}
            ...
        </div>
    </div>
{/each}

To me, this issue is not an issue in Svelte, but an issue on how developers are using it.

How does it happen ?

When you have a DOM which is just inside an Svelte block, like {#if …} or {#each …}, and a JS script is removing this DOM. The removal is done by JavaScript outside of the knowledge of Svelte. At the end, when a page change (e.g. SPA routing), when Svelte kills all the DOM of the page, there’s no element remaining in that Svelte block, and the crash occurs.

It can be for example :

  • Your JS calls dom.remove() for a DOM just inside a Svelte block
  • An icon script, changing a span DOM directly inside a Svelte block into a SVG (this removes the span DOM)
  • You have {value} which can be empty directly inside a Svelte block (to be confirmed)

How to fix it?

Basically, make sure there isn’t any script removing a component or DOM directly inside a Svelte block. A way is to wrap the DOM in a DIV or SPAN new block. So that when removing it, there’s still a DOM inside the Svelte block. An other way is to prevent using any JS that removes a DOM. Not easy way because there are some scripts required sometimes, we can’t escape this. This way can mean “use more Svelte” to achieve your goal.

In a way, the core issue is that Svelte is unsynced with the DOM, and is not aware of a DOM removal, than when it closes it, the element was already removed and doesn’t exist anymore. So wrap it as a child, or refrain to use any DOM removal from JS. My PoV is that this is not really an issue in Svelte.

Still, adding if(node.parentNode) can help, because if there’s nothing to delete, it won’t crash anymore. For now, just make sure there’s always something to delete.

Also, this can make it clear as a warning in the documentation. I haven’t seek about this in the doc so far.

#2086 (comment)

I encountered this bug in a similar context — trying to toggle/destroy a custom Marker component on a mapbox map, built with beyonk/svelte-mapbox library. Likewise, the fix that @byt3rr specified from @ciri worked for me.

Change line 306 (this line number changes with updates) of node_modules/svelte/internal/index.mjs to:

function detach(node) {
	if(node.parentNode) {
		node.parentNode.removeChild(node);
	}
}

It appears the line number to make this change (currently 306) periodically changes with new updates. For future reference, to find where to insert this snippet, just look in node_modules/svelte/internal/index.mjs for the function:

function detach(node) {
    node.parentNode.removeChild(node);
}

And replace that function with:

function detach(node) {
	if(node.parentNode) {
		node.parentNode.removeChild(node);
	}
}

https://github.com/sveltejs/svelte/issues/2086#issuecomment-787896877 @jycouet You asked me how I managed to workaround the issue. You will find the “root cause” in npm_modules/svelte/internal/index.js line 202 (varies with your svelte version) For local development you can simple change it there but this will not help you for production. My simple and really stupid solution is to string replace it during the bundle Changes in my rollup.config.js transform(code, id) { return code.replace('node.parentNode.removeChild(node)', 'if(node.parentNode)node.parentNode.removeChild(node)'); } } I checked the issue also with a conditional breakpoint and a lot of things were related to animations with svelte/transition. I changed all transition to local transitions. But like I said it is still an issue for us and I decided to dirty fix it with the string replacement. When I find some time I can try again to isolate the issue with conditional breakpoints.

We do similar things like you: Open closing dialogs and overlays and changing big parts of the DOM. We have a pretty interactive page (mini games) and we are using a lot of different components which are dynamically shown and hidden all the time.

Thx a lot @hallvors , I never use this debugging way! And it worked very well in my repo.

It’s in a component where I have:

<script lang="ts">
    ....
</script>

{#if showEdit}
    ...
{/if}

=> no parentNode.

I updated this component like this:

<script lang="ts">
    ....
</script>

<div>
  {#if showEdit}
      ...
  {/if}
</div>

And now, I don’t have the error anymore.

I tried to reproduce here https://svelte.dev/repl/747b8a3626624afab7f1640635190591?version=3.34.0 But I don’t manage to have my not working behavior. 😞

Not sure what to do now. Should we close the issue? Or?

This problem is still happening witn the latest svelte. I’m not sure if there was a regression here:

“svelte”: “^3.46.6”,

function detach(node) {
    node.parentNode.removeChild(node);
}

Hello there ! I can confirm one of by beta users stumbled upon this bug while using automatic translations on Google Chrome. When I suggested her to try to turn the translation off, it worked like a charm.

I have this behavior with "svelte": "3.34.0" (it was also the case with "3.32.3") (Actually, my exact message is Uncaught TypeError: Cannot read property 'removeChild' of null, there is no (in promise))

Unfortunately, I can’t share my repo, and I don’t find the root cause to isolate the issue and create a repl. Fortunately, I ❤️ Svelte and will spend time to find how to reproduce it. I hope to be able to create a repl soon

Wrapping the entire block in a div resolved it for me: <div>{#if}...{/if}</div>

In my case, I also needed to the wrap the component inside the conditional block in an extra div.

Before

{#if isTextVisible}
  <Text>Hello World</Text>
{/if}

after

<div>
  {#if isTextVisible}
    <div>
      <Text>Hello World</Text>
    </div>
  {/if}
</div>

Thank you @antonio-fr for the guidance. You put me on the right track after many hours of aimless debugging.

If it helps anyone else, my situation was a top-level <Nav /> element shown conditionally:

{#if $state.navigation}
    <nav transition:fade|local>
    ...
    </nav>
{/if}

Wrapping the entire block in a div resolved it for me: <div>{#if}...{/if}</div>

I have a repro of this issue involving Twitter embeds that are rendered within a modal where embed code is rendered using @html — the issue reproduces when closing the modal if the content rendered by @html is not wrapped in a tag:

https://github.com/pushred/svelte-issue-6037-repro/blob/main/src/routes/index.svelte

(freshly initialized SvelteKit project, only changes are in the above file)

I suspect this is due to the Twitter’s widgets.js swapping out the original markup with it’s own. As someone mentioned in #2086 this seems to get Svelte in a state where it is “confused” and tries to cleanup the prior DOM state.

My repro also has an option that demonstrates the workaround of wrapping @html in a tag.

Sapper-based project, this in a .svelte file crashes the app and requires a reload on navigating away from the relevant Sapper route:

<div class="note-box" bind:clientWidth={elemWidth}>
  {@html svg}
</div>

The element whose parentNode no longer exists is an IFRAME and I assume it has been added to the DIV to help measure width and/or detect resizes. It seems that the logic cleaning up @html blocks on unmount does not take into account the presence of this IFRAME, and the later logic that attempts to clean up the IFRAME does not consider that it might no longer be in the DOM?

I attempted a demo here but I don’t know how to make it un-mount the component like it does during navigation - or perhaps there’s some other trigger I have not discovered. I hope this helps anyway. https://svelte.dev/repl/e67564eaa8d24312bbeb91e0a402f7fc?version=3.34.0 Edit: using svelte@3.34.0 for project now, still seeing the problem.

The web is an open development platform - users may run extensions that do any sort of crazy things inside the DOM, they may even run bookmarklets or change the DOM directly in devtools. Svelte-generated code simply has to be prepared for the DOM changing underneath it, and IMHO it is definitely a bug in Svelte to crash because of a no-longer-valid reference to the DOM.

Related to @apop880 comment (https://github.com/sveltejs/svelte/issues/6037#issuecomment-810304989), I encountered this issue recently when using fontawesome icons that I did not have wrapped in <span> tags - once I wrapped them in <span> tags, went away. Was not an issue previously but I am unsure how many versions ago that was.

I think the Svelte developers likely want to fix something here, so let’s leave that decision to them 😃

This happened for me when using Fathom Analytics.

The piece of code that was causing the issues was the following

<body data-sveltekit-preload-data="hover">
    %sveltekit.body%
</body>

Wrapping %sveltekit.body% in a tag resolved the issue.

<body data-sveltekit-preload-data="hover">
    <main class="container">%sveltekit.body%</main>
</body>

Here is the codebase I am working on before and after.

I hit this bug again yesterday, when trying to add Google Maps JS API to a Svelte-based site. Even though I’m already following this issue and tried several workarounds it kept crashing and it was not at all obvious why.

I was following some online guides adding the Google maps JS api with an actual <script src.. tag, once I tried to add it using document.createElement('script')… instead the problem was resolved (why?!?). But it took quite some time figuring it out, and hitting this again after the bug has been open for years and has an open PR does not give me much confidence in Svelte development 😢

(Sorry this comment is basically just a +1 and a rant, but it was rather frustrating. I think Svelte is an amazing concept with lots of potential…)

You will find the “root cause” in npm_modules/svelte/internal/index.js line 202 (varies with your svelte version) For local development you can simple change it there but this will not help you for production. My simple and really stupid solution is to string replace it during the bundle Changes in my rollup.config.js transform(code, id) { return code.replace('node.parentNode.removeChild(node)', 'if(node.parentNode)node.parentNode.removeChild(node)'); } }

Thanks for this workaround. Instead of configuring rollup to change output bundle, I use https://www.npmjs.com/package/patch-package - this works both for local development and for production bundle

Do you know what element it crashes when it tries to remove? In devtools, you can set a conditional breakpoint on the line that throws and make the condition !element.parentNode - then it will stop just before throwing.