You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中使用framer-motion报错:createContext不是函数求助

解决Next.js中framer-motion服务端渲染的createContext错误

原因排查与解决方案

1. 验证React版本兼容性

framer-motion新版本依赖React 18+,若项目中React版本过低,会导致createContext这类基础API无法正常调用。

  • 打开package.json确认react和react-dom版本≥18.0.0
  • 版本不足时执行升级命令:
    npm install react@latest react-dom@latest
    
    或使用yarn:
    yarn add react@latest react-dom@latest
    

2. 强制组件在客户端运行

Next.js 13+ App Router默认启用服务端组件(RSC),而framer-motion依赖React客户端API(如Context、useEffect),无法在服务端组件中直接使用。

  • 在使用framer-motion的组件文件顶部添加'use client'指令:
    'use client';
    import { motion } from 'framer-motion';
    
    export default function MyMotionComponent() {
      return <motion.div animate={{ x: 100 }}>Hello</motion.div>;
    }
    

3. 清理缓存并重建项目

webpack缓存可能残留依赖异常,即使重装依赖也无法解决:

  • 删除项目根目录下的.next文件夹和node_modules/.cache目录
  • 清除包管理器缓存:
    npm cache clean --force
    
    或
    yarn cache clean
    
  • 重新安装依赖并构建:
    npm install && npm run build
    

4. 调整framer-motion版本

部分framer-motion版本与Next.js App Router存在兼容性问题,可尝试切换版本:

  • 安装最新稳定版:
    npm install framer-motion@latest
    
  • 若最新版仍有问题,回退到已知兼容版本:
    npm install framer-motion@10.16.4
    

5. 排查自定义webpack配置

若项目修改过webpack配置,可能导致React模块解析异常:

  • 检查next.config.js中的webpack配置,确保未篡改React的解析规则
  • 暂时移除自定义webpack配置,重新构建验证是否为配置问题

内容的提问来源于stack exchange,提问作者Arondhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:05:01