Skip to content

fix: 修复 React Hook 在回调函数中调用的规则违反问题#5

Open
phaseddd wants to merge 2 commits intoliujuntao123:mainfrom
phaseddd:fix/react-hooks-rules-violation
Open

fix: 修复 React Hook 在回调函数中调用的规则违反问题#5
phaseddd wants to merge 2 commits intoliujuntao123:mainfrom
phaseddd:fix/react-hooks-rules-violation

Conversation

@phaseddd
Copy link
Copy Markdown

概述

  • 修复 ESLint 报错:"React Hook useEngine cannot be called inside a callback"
  • 使用状态 + useEffect 模式替代在 setTimeout 回调中非法调用 Hook 的方式

改动内容

  • 新增 pendingHistory 状态,用于保存待恢复的历史记录
  • 新增 useEffect,监听引擎类型切换完成后自动恢复历史记录
  • 移除 onConfirm 回调中使用 setTimeout 非法调用 Hook 的代码

修复原因

React Hooks 规则要求:Hook 只能在组件顶层调用,不能在回调函数、条件语句或循环中调用。

原代码在 setTimeout 回调中调用了 useEngine(),违反了此规则。

新方案使用 React 的状态和副作用系统:

  1. 将待恢复的历史记录保存到状态
  2. 触发引擎类型切换
  3. useEffect 检测到引擎类型与待恢复历史的目标类型匹配时
  4. 自动执行历史记录恢复

Replace invalid useEngine() call inside setTimeout callback with
a state-based approach using pendingHistory + useEffect pattern.

This fix addresses the ESLint error:
"React Hook useEngine cannot be called inside a callback"

Changes:
- Add pendingHistory state to store history awaiting restoration
- Add useEffect to monitor engine switch and auto-restore history
- Remove setTimeout with invalid Hook call from onConfirm callback
@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Dec 15, 2025

@phaseddd is attempting to deploy a commit to the liujuntao123's projects Team on Vercel.

A member of the Team first needs to authorize it.

- 添加 node_modules/** 到忽略列表,避免检查依赖包
- 指定 lint 命令只检查 app/components/hooks/lib 目录
- 禁用 Next.js 16+ 过于严格的 React Compiler 规则
  - react-hooks/preserve-manual-memoization
  - react-hooks/set-state-in-effect
  - react-hooks/immutability
- 将 exhaustive-deps 改为 warn 级别
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant