diff --git a/packages/next/src/client/image.tsx b/packages/next/src/client/image.tsx index 66f5dd5707926..2f71d1ac87aba 100644 --- a/packages/next/src/client/image.tsx +++ b/packages/next/src/client/image.tsx @@ -276,7 +276,7 @@ function handleLoading( img['data-loaded-src'] = src const p = 'decode' in img ? img.decode() : Promise.resolve() p.catch(() => {}).then(() => { - if (!img.parentNode) { + if (!img.parentElement || !img.isConnected) { // Exit early in case of race condition: // - onload() is called // - decode() is called but incomplete diff --git a/test/integration/next-image-new/default/pages/should-not-warn-unmount.js b/test/integration/next-image-new/default/pages/should-not-warn-unmount.js new file mode 100644 index 0000000000000..957bc4cd0ce6a --- /dev/null +++ b/test/integration/next-image-new/default/pages/should-not-warn-unmount.js @@ -0,0 +1,25 @@ +import Image from 'next/image' +import { useEffect, useState } from 'react' + +export default function Home() { + const [displayImage, setDisplayImage] = useState(true) + + useEffect(() => { + // This will cause the image to unmount. + // See https://github.com/vercel/next.js/issues/40762 + setDisplayImage(false) + }, []) + + return ( +
+

Should not warn on unmount

+
+ {displayImage ? ( +
+ alt +
+ ) : null} +
+
+ ) +} diff --git a/test/integration/next-image-new/default/test/index.test.ts b/test/integration/next-image-new/default/test/index.test.ts index 84c726a1632a4..2c30da71403f2 100644 --- a/test/integration/next-image-new/default/test/index.test.ts +++ b/test/integration/next-image-new/default/test/index.test.ts @@ -1167,6 +1167,16 @@ function runTests(mode) { 'Image with src "/wide.png" has "fill" but is missing "sizes" prop. Please add it to improve page performance. Read more:' ) }) + it('should not log warnings when image unmounts', async () => { + browser = await webdriver(appPort, '/should-not-warn-unmount') + await waitFor(1000) + const warnings = (await browser.log('browser')) + .map((log) => log.message) + .join('\n') + expect(warnings).not.toContain( + 'Image with src "/test.jpg" has "fill" and parent element' + ) + }) } }) // Tests that use the `unsized` attribute: