Next.js构建报错[TypeError: Cannot read properties of null (reading 'useContext')]求助
问题描述
用npx create-next-app@latest创建Next.js项目,安装过程无异常,生成的package.json配置如下:
{ "name": "test_4", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev --turbopack", "build": "next build --turbopack", "start": "next start" }, "dependencies": { "react": "19.1.0", "react-dom": "19.1.0", "next": "15.5.4" }, "devDependencies": { "typescript": "^5", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", "@tailwindcss/postcss": "^4", "tailwindcss": "^4" } }
执行npm run build时出现以下错误,预渲染/404页面失败导致构建终止:
> test_1@0.1.0 build > next build --turbopack ▲ Next.js 15.5.5 (Turbopack) Creating an optimized production build ... ✓ Finished writing to disk in 24ms ✓ Compiled successfully in 1915ms ✓ Linting and checking validity of types ✓ Collecting page data [TypeError: Cannot read properties of null (reading 'useContext')] Error occurred prerendering page "/404". Read more: https://nextjs.org/docs/messages/prerender-error [TypeError: Cannot read properties of null (reading 'useContext')] Export encountered an error on /_error: /404, exiting the build. ⨯ Next.js build worker exited with code: 1 and signal: null
已尝试移除--turbopack参数、清理npm缓存、删除_npx缓存文件夹、重新安装依赖、创建not-found.tsx和error.tsx页面等方法,均未解决问题。
问题原因与解决方法
问题原因
- React 19与Next.js 15兼容性冲突:React 19引入了上下文处理的新逻辑,Next.js 15的Turbopack构建器在预渲染404页面时,无法正确适配这些变化,导致
useContext调用时上下文对象为null。 - Tailwind CSS 4的不稳定因素:Tailwind CSS 4处于早期版本,其构建集成与Next.js 15的预渲染流程存在未适配的问题,进一步加剧了构建失败的概率。
解决步骤
降级React及相关类型依赖到稳定兼容版本
修改package.json中的依赖版本,将React降级到Next.js 15官方推荐的18.2.0版本,同时同步更新类型依赖:{ "dependencies": { "react": "18.2.0", "react-dom": "18.2.0", "next": "15.5.4" }, "devDependencies": { "typescript": "^5", "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "tailwindcss": "^3.4.1", "postcss": "^8.4.38" } }注:移除
@tailwindcss/postcss依赖,因为Tailwind CSS 3.x不需要该包。清理缓存并重新安装依赖
执行以下命令彻底清理旧依赖和缓存:rm -rf node_modules package-lock.json npm cache clean --force npm install调整构建命令(可选)
若仍有问题,可暂时移除build命令中的--turbopack参数,使用Next.js默认构建器:"scripts": { "dev": "next dev", "build": "next build", "start": "next start" }重新执行构建
运行npm run build验证问题是否解决。
内容的提问来源于stack exchange,提问作者Spektor225
相关产品推荐
相关产品推荐

