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
相关产品推荐
相关产品推荐

