React Framer Motion移除组件时getComputedStyle报错求助
Framer Motion移除DOM时触发getComputedStyle错误的解决办法
我用Framer Motion实现了一个带入场动画的成功提示组件,代码如下:
<motion.span ref={successRef} className="success" key="tab2Success" aria-live="assertive" whileInView="visible" initial="hidden" viewport={{ once: false }} transition={{ duration: 0.4 }} variants={{ visible: { opacity: 1, height: "auto", marginBottom: 14, }, }} > Création ajoutée avec succès ! </motion.span>
当组件从DOM中移除时,触发以下错误:
Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'. TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'. at convertChangedValueTypes (webpack://brice/./node_modules/framer-motion/dist/es/render/dom/utils/unit-conversion.mjs?:85:34) at checkAndConvertChangedValueTypes (webpack://brice/./node_modules/framer-motion/dist/es/render/dom/utils/unit-conversion.mjs?:199:33) at unitConversion (webpack://brice/./node_modules/framer-motion/dist/es/render/dom/utils/unit-conversion.mjs?:227:11) at parseDomVariant (webpack://brice/./node_modules/framer-motion/dist/es/render/dom/utils/parse-dom-variant.mjs?:18:80) at HTMLVisualElement.makeTargetAnimatableFromInstance (webpack://brice/./node_modules/framer-motion/dist/es/render/dom/DOMVisualElement.mjs?:43:105) at HTMLVisualElement.makeTargetAnimatable (webpack://brice/./node_modules/framer-motion/dist/es/render/VisualElement.mjs?:329:21) at animateTarget (webpack://brice/./node_modules/framer-motion/dist/es/render/utils/animation.mjs?:82:105) at animateVisualElement (webpack://brice/./node_modules/framer-motion/dist/es/render/utils/animation.mjs?:36:21) at eval (webpack://brice/./node_modules/framer-motion/dist/es/render/utils/animation-state.mjs?:24:151) at Array.map (<anonymous>)
已尝试用AnimatePresence initial={false}包裹组件,但问题依旧。
解决办法
1. 补全退出动画并正确配置AnimatePresence
当前代码仅定义了visible变体,缺少卸载时的hidden状态,且whileInView的视图监听逻辑和组件卸载动画冲突,导致Framer Motion在组件移除后仍尝试读取DOM样式。
修正代码:
import { AnimatePresence, motion } from "framer-motion"; // 父组件中通过showSuccess状态控制显示 {showSuccess && ( <AnimatePresence> <motion.span ref={successRef} className="success" key="tab2Success" aria-live="assertive" initial="hidden" animate="visible" exit="hidden" transition={{ duration: 0.4 }} variants={{ visible: { opacity: 1, height: "auto", marginBottom: 14, }, hidden: { opacity: 0, height: 0, marginBottom: 0, overflow: "hidden" // 避免内容溢出 } }} > Création ajoutée avec succès ! </motion.span> </AnimatePresence> )}
- 增加
exit="hidden"绑定退出动画 - 替换
whileInView为animate="visible",由状态控制动画触发 - 确保
AnimatePresence直接包裹目标组件,且组件有唯一key
2. 清理ref引用避免内存泄漏
如果使用useRef绑定元素,组件卸载时Framer Motion可能仍尝试访问已销毁的DOM节点,可在卸载时手动清空ref:
import { useEffect, useRef } from "react"; const successRef = useRef(null); useEffect(() => { return () => { successRef.current = null; }; }, []);
3. 升级Framer Motion版本
部分旧版本存在DOM卸载后样式读取的bug,升级到最新稳定版可解决:
npm update framer-motion # 或 yarn 命令 yarn upgrade framer-motion
内容的提问来源于stack exchange,提问作者Jeje Pro
相关产品推荐
相关产品推荐

