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

使用Next.js+Antd组件触发TypeError: Cannot set properties of undefined (setting 'hook')

解决Next.js集成Antd时出现TypeError: Cannot set properties of undefined (setting 'hook')的问题

常见原因

  • Antd与React/Next.js版本不兼容
  • Next.js App Router中在服务端组件内使用了Antd客户端组件
  • 旧的按需引入配置(如babel-plugin-import)与Antd 5冲突
  • 缓存导致的依赖异常

具体解决步骤

1. 确认版本兼容性

确保你的项目依赖版本满足:

  • React >= 18.0.0
  • Next.js >= 13.0.0
  • Antd >= 5.0.0

查看package.json中的依赖版本,不满足则升级:

npm install react@latest next@latest antd@latest
# 或使用yarn
yarn add react@latest next@latest antd@latest

2. 在客户端组件中使用Antd组件

Next.js App Router默认创建的是服务端组件,而Antd组件依赖React Hooks(如useState、useEffect),必须在客户端组件中使用。在组件文件最顶部添加'use client'指令:

'use client'; // 必须放在文件第一行

import { useState } from 'react';
import { Button, Modal, Tooltip } from 'antd';
import { EditOutlined, CheckOutlined, UploadOutlined } from '@ant-design/icons';

export default function YourComponent() {
  const [isModalOpen, setIsModalOpen] = useState(false);

  return (
    <>
      <div className="d-flex gap-2">
        <Tooltip title="Edit">
          <EditOutlined className="h5 pointer text-warning" />
        </Tooltip>
        <Tooltip title="Publish">
          <CheckOutlined className="h5 pointer text-success ml-2" />
        </Tooltip>
      </div>

      <Button
        className="w-100"
        onClick={() => setIsModalOpen(true)}
        type="primary"
        shape="round"
        size="large"
        icon={<UploadOutlined />}
      >
        Open modal
      </Button>

      <Modal
        title="Modal title"
        centered
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        footer={null}
      >
        <p>Some contents...</p>
      </Modal>
    </>
  );
}

3. 移除旧的按需引入配置

Antd 5原生支持Tree Shaking,无需额外配置babel-plugin-import。如果你的项目中存在以下配置,直接删除:

  • babel.config.js或.babelrc中的babel-plugin-import配置
  • next.config.js中相关的按需引入插件

4. 清除缓存并重新构建

删除项目中的缓存文件,重新安装依赖并构建:

# 删除Next.js缓存和node_modules
rm -rf .next node_modules
# 重新安装依赖
npm install
# 重新启动开发服务器
npm run dev

额外说明

如果是使用Next.js Pages Router的项目,除了上述步骤,还要确保没有在_app.js中错误地使用服务端渲染逻辑包裹Antd组件,保持组件的客户端渲染特性即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:38:49