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

NextJS引入Framer Motion遇双重报错:createContext与JSON解析问题

NextJS 引入 Framer Motion 后报错的解决方法

问题详情

在 NextJS 项目中引入 Framer Motion 库后,先触发报错:

TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.

在文件顶部添加 'use client'; 指令后,又出现新报错:

error - SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse ()

相关代码如下:

'use client';

import Image from 'next/image'
import { Teko, Syncopate , Sofia_Sans_Condensed, Anton} from 'next/font/google'
import { FaTelegramPlane} from 'react-icons/fa'
import { FaDiscord} from 'react-icons/fa'
import { BsShop} from 'react-icons/bs'
import Link from 'next/link'
import {motion as m} from "framer-motion"

export default function Home() {
  return (
   <m.main className='container'>
       <h1>Hello World</h1>
    </m.main>
) 
}

解决方法

关于第一个报错

添加 'use client'; 是正确操作,因为 Framer Motion 依赖 React Context,只能在客户端组件中运行,这个步骤没问题。

针对第二个 JSON 解析报错,按以下步骤排查:

  • 检查项目环境变量:确保所有环境变量都已正确赋值,没有出现 undefined 的情况。若某个环境变量未被正确设置,代码尝试对其执行 JSON.parse 时就会触发该错误。
  • 排查 JSON.parse 调用:搜索项目中所有使用 JSON.parse 的位置,确认传入的参数不是 undefined 或无效的 JSON 字符串。
  • 清理缓存与依赖:删除 .next 文件夹和 node_modules,重新执行 npm install 和 npm run dev,清除可能存在的缓存异常。
  • 检查配置文件:查看 next.config.js 中的配置,确保没有错误的 JSON 格式或无效配置项,比如 env 字段中的值是否合法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 21:47:25