概述
在使用 Next.js 项目时,可能会遇到以下错误提示:
plaintext
596-e2c30dd291e774da.js:1 Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
该错误通常是由于 React 或其相关库的配置问题引起的。本文将介绍如何解决这一问题。
错误原因
根据 React 官方文档的提示,Minified React 错误 #321 可能由以下三种情况造成:
- 确定 - react和- react-dom是相同版本:- 确保项目中 react和react-dom的版本一致。
 
- 确保项目中 
- 确定自己的代码没有违背 Hooks 的使用准则: - 确保在代码中正确使用 React Hooks,遵循 Hooks 的规则。
 
- 确定项目中是否引入了多个 - react实例:- 确保项目中没有重复引入多个 react实例,这可能导致冲突。
 
- 确保项目中没有重复引入多个 
解决办法
方法一:确保 react 和 react-dom 版本一致
- 检查 - package.json文件:- 确保 react和react-dom的版本相同。
 json- "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0" }
- 确保 
- 安装依赖: - 运行以下命令安装或更新依赖。
 bash- npm install
方法二:确保 Hooks 使用正确
根据 React 官方文档,Hooks 的使用准则包括:
- 只在顶层调用 Hooks:不要在循环、条件或嵌套函数中调用 Hooks。
- 只在 React 函数组件或自定义 Hooks 中调用 Hooks:不要在普通的 JavaScript 函数中调用 Hooks。
示例代码
正确使用 Hooks:
jsx
import React, { useState, useEffect } from 'react';
function ExampleComponent() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
错误使用 Hooks:
jsx
import React, { useState, useEffect } from 'react';
function ExampleComponent() {
  if (count > 0) {
    const [count, setCount] = useState(0); // 错误:在条件语句中调用 Hooks
  }
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
方法三:确保没有引入多个 react 实例
- 检查 - node_modules中的- react实例:- 确保项目中没有重复的 react实例。
 
- 确保项目中没有重复的 
- 使用 - npm ls react检查依赖树:- 运行以下命令检查项目中 react的依赖树。
 bash- npm ls react
- 运行以下命令检查项目中 
- 解决重复依赖: - 如果发现重复的 react实例,可以通过以下方法解决:- 删除 - node_modules并重新安装依赖:bash- rm -rf node_modules npm install
- 使用 - resolutions字段(适用于 Yarn):json- "resolutions": { "react": "^18.2.0", "react-dom": "^18.2.0" }
- 使用 - npm dedupe:bash- npm dedupe
 
 
- 如果发现重复的 
实际排查
在你的项目中,实际排查发现问题是由于 Hooks 使用不当造成的。具体来说,某些 Hooks 在条件语句中被调用,违反了 Hooks 的使用准则。移除这些不当的 Hooks 调用后,问题得到解决。
示例代码
错误代码:
jsx
import React, { useState } from 'react';
function ExampleComponent() {
  if (true) {
    const [count, setCount] = useState(0); // 错误:在条件语句中调用 Hooks
  }
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
修正后的代码:
jsx
import React, { useState } from 'react';
function ExampleComponent() {
  const [count, setCount] = useState(0); // 正确:在顶层调用 Hooks
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}