@@ -76,6 +76,13 @@ export function VirtualElement({
7676 const isTransitioning = useRef ( false )
7777
7878 const isCurrentlyObserving = useRef ( false )
79+ const isMountedRef = useRef ( true )
80+
81+ useEffect ( ( ) => {
82+ return ( ) => {
83+ isMountedRef . current = false
84+ }
85+ } , [ ] )
7986
8087 const styleObj = useMemo < React . CSSProperties > (
8188 ( ) => ( {
@@ -91,11 +98,13 @@ export function VirtualElement({
9198 )
9299
93100 const handleResize = useCallback ( ( ) => {
101+ if ( ! isMountedRef . current ) return
94102 if ( ref ) {
95103 // Show children during measurement
96104 setIsShowingChildren ( true )
97105
98106 requestAnimationFrame ( ( ) => {
107+ if ( ! isMountedRef . current ) return
99108 const measurements = measureElement ( ref , placeholderHeight )
100109 if ( measurements ) {
101110 setMeasurements ( measurements )
@@ -296,6 +305,7 @@ export function VirtualElement({
296305 }
297306 idleCallback = window . requestIdleCallback (
298307 ( ) => {
308+ if ( ! isMountedRef . current ) return
299309 // Measure the entire wrapper element instead of just the childRef
300310 if ( ref ) {
301311 const measurements = measureElement ( ref , placeholderHeight )
@@ -495,6 +505,7 @@ export class ElementObserverManager {
495505 this . observedElements . delete ( element )
496506 this . resizeObserver . unobserve ( element )
497507 this . pruneDetachedObservedElements ( )
508+ this . mutationObserver . disconnect ( )
498509
499510 if ( this . observedElements . size === 0 ) {
500511 if ( this . pendingReconnectFrame ) {
@@ -511,7 +522,6 @@ export class ElementObserverManager {
511522 this . pendingReconnectFrame = undefined
512523
513524 // MutationObserver has no per-element unobserve, so we reconnect once per frame.
514- this . mutationObserver . disconnect ( )
515525 this . pruneDetachedObservedElements ( )
516526
517527 if ( this . observedElements . size === 0 ) {
@@ -520,6 +530,7 @@ export class ElementObserverManager {
520530 }
521531
522532 this . observedElements . forEach ( ( _ , el ) => {
533+ if ( ! document . contains ( el ) ) return
523534 this . mutationObserver . observe ( el , {
524535 childList : true ,
525536 subtree : true ,
0 commit comments