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

Next.js Page Router出现useState读取null属性错误,App Router正常

问题排查:Next.js Page Router中React Hook库报错TypeError: Cannot read properties of null (reading 'useState')

问题根源

你的tsup打包配置未正确将React标记为外部依赖,导致库打包时将React代码嵌入产物中。Next.js Page Router默认使用CommonJS模块系统,这种情况下库内的React实例与宿主项目的React实例冲突,进而触发useState读取null的错误;而App Router采用ES模块加载,规避了这个问题。

解决方案

1. 修正tsup配置

修改项目根目录的tsup.config.ts,添加external配置并确保同时输出CommonJS和ES模块格式:

import { defineConfig } from 'tsup';

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['cjs', 'esm'],
  external: ['react', 'react-dom'], // 让宿主项目提供React依赖
  dts: true,
  clean: true,
});

2. 完善package.json的模块入口

确保package.json中正确声明不同模块系统的入口:

{
  "main": "./dist/index.cjs",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  }
}

3. 重新打包并清理测试项目缓存

# 重新打包库
npm run build

# 清理Page Router示例项目的缓存和依赖
cd example/nextjs-page-router
rm -rf node_modules .next
npm install
npm run dev

额外检查

确保你的Hook源码中正确导入React:

import { useState } from 'react';

export const useCounter = () => {
  const [count, setCount] = useState(0);
  const increment = () => setCount(count + 1);
  return { count, increment };
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 12:32:50