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

NextJS中使用Framer Motion组件出现createContext报错求助

解决Next.js + Sanity + Framer Motion的createContext报错问题

这个报错的核心原因是Next.js 13+的App Router默认所有组件都是服务器组件,而Framer Motion依赖React的createContext API,这只能在客户端组件里运行,直接使用就会触发错误。

给你直接可行的解决步骤:

  • 找到引入Framer Motion的组件文件(比如你的Header组件),在文件最顶部添加"use client";指令,位置要在所有import语句之前,示例代码:
"use client";

import { motion } from "framer-motion";
import React from "react";

export default function Header() {
  return (
    <motion.header initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
      {/* 你的组件内容 */}
    </motion.header>
  );
}
  • 如果你在多个组件里都用到了Framer Motion,每个涉及的组件都需要添加这个指令——只要组件里用到了客户端专属API(比如motion组件、useState、useEffect等),都必须显式标记为客户端组件。

你提到仅渲染h1时Header能正常工作,是因为纯静态的h1属于服务器组件范畴,不需要调用客户端API;而添加motion组件后触发了客户端API的使用,所以必须声明"use client"才能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:15:34