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

使用useHistory未解构对象时触发exhaustive-deps不一致警告

使用useHistory时避免exhaustive-deps警告的正确方式

问题重现

当直接使用useHistory返回的完整对象并引用其方法作为依赖时,会触发ESLint的exhaustive-deps警告:

const history = useHistory();

useEffect(() => {
  history.replace({ search: '' });
}, [history.replace]);

const change = useCallback(() => {
  history.replace({ search: '' });
}, [history.replace]);

收到的警告提示:

React Hook useCallback has a missing dependency: 'history'. Either include it or remove the dependency array

问题原因

ESLint的exhaustive-deps规则会严格检查回调中依赖的引用关系。history.replace是挂载在history对象上的方法,当你把history.replace加入依赖数组时,规则会检测到回调内部实际依赖了history这个对象(方法的执行依赖原对象上下文),因此判定你遗漏了history作为依赖。

尽管useHistory返回的history对象及其方法在组件生命周期内引用都是稳定的,但直接引用history.replace的写法会让ESLint无法正确识别这一点,从而误触发警告。

解决方法

通过解构useHistory的返回值,直接提取需要的方法,再将该方法作为依赖传入数组:

const { replace } = useHistory();

useEffect(() => {
  replace({ search: '' });
}, [replace]);

const change = useCallback(() => {
  replace({ search: '' });
}, [replace]);

这种写法既符合ESLint规则,代码更简洁,同时不会触发exhaustive-deps警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 10:57:33