Next.js项目使用react-hot-toast报错:useState未从React导出
解决Next.js中react-hot-toast导入报错:'useState' is not exported from 'react'
问题描述
在Next.js项目中导入react-hot-toast库时,出现如下错误:
error - ./node_modules/react-hot-toast/dist/index.mjs
Attempted import error: 'useState' is not exported from 'react' (imported as 'j').
相关代码:
- Toast组件文件(
@/components/ui/toast.tsx):
'use client'; import { Icons } from '@/components/Icons'; import { cn } from '@/lib/utils'; import * as React from 'react'; import hotToast, { Toaster as HotToaster } from 'react-hot-toast'; export const Toaster = HotToaster;
- RootLayout中使用:
import '@/styles/globals.css'; import { Inter } from 'next/font/google'; import { cn } from '@/lib/utils'; import Providers from '@/components/Providers'; import Navbar from '@/components/Navbar'; import { Toaster } from '@/components/ui/toast'; const inter = Inter({ subsets: ['latin'] }); export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang='en' className={cn('bg-white text-slate-900 antialiased', inter.className)} > <body className='min-h-screen bg-slate-50 dark:bg-slate-900 antialiased'> <Providers> <Toaster position='bottom-right' /> {/* @ts-expect-error Server Component */} <Navbar /> {children} </Providers> <div className='h-40 md:hidden' /> </body> </html> ); }
解决方案
1. 检查并更新依赖版本
这个错误大多是因为react-hot-toast与React/Next.js版本不兼容导致的。执行以下步骤:
- 查看当前依赖版本:
npm list react react-hot-toast - 更新到最新兼容版本:
npm install react@latest react-dom@latest react-hot-toast@latest
2. 修正组件导入写法
调整Toast组件文件的导入方式,确保符合react-hot-toast的标准用法:
'use client'; import { cn } from '@/lib/utils'; import { Toaster, toast } from 'react-hot-toast'; // 直接导出组件和toast方法即可,无需额外重命名 export { Toaster, toast };
3. 清除缓存并重启项目
依赖更新后,清除Next.js缓存并重新构建,避免缓存导致的异常:
rm -rf .next node_modules package-lock.json npm install npm run dev
4. 确认客户端组件标记
确保@/components/ui/toast.tsx文件顶部的'use client';标记存在,因为react-hot-toast依赖React hooks,必须在客户端组件中使用。
原因说明
该错误本质是react-hot-toast内部使用的React导入方式与当前项目的React版本不匹配,比如旧版库可能使用了错误的命名导入路径,或者依赖安装时出现了版本冲突,导致React的核心hooks无法被正确识别。
内容的提问来源于stack exchange,提问作者ludinj
相关产品推荐
相关产品推荐

