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

解决useEffect中使用useFormik时的ESLint依赖缺失问题

解决方法

方法一:解构出稳定的setFieldValue函数

useFormik返回的setFieldValue是不会随组件渲染变化的稳定函数,直接解构它并加入依赖数组,既满足ESLint要求,又不会因为表单其他值变动触发不必要的useEffect执行:

const { setFieldValue } = useFormik()
const store = useZustandStore()

useEffect(() => {
  if (store.someSearchItems.length) {
    const initial = store.someSearchItems[0].value as string;
    setFieldValue('LIST_VALUE', initial);
  }
}, [store.someSearchItems, setFieldValue]);

方法二:用useRef缓存formik对象

如果不想解构,可以用useRef存储formik实例,确保在useEffect里能访问到最新的formik,同时不用把整个formik加入依赖数组:

const formik = useFormik()
const store = useZustandStore()
const formikRef = useRef(formik);

// 每次渲染更新ref指向最新的formik
useEffect(() => {
  formikRef.current = formik;
});

useEffect(() => {
  if (store.someSearchItems.length) {
    const initial = store.someSearchItems[0].value as string;
    formikRef.current.setFieldValue('LIST_VALUE', initial);
  }
}, [store.someSearchItems]);

方法三:临时忽略ESLint错误(不推荐)

如果以上方法都不适用,可以在useEffect上方添加注释单独忽略该ESLint规则,但这是下策,尽量优先用前两种方法:

const formik = useFormik()
const store = useZustandStore()

// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
  if (store.someSearchItems.length) {
    const initial = store.someSearchItems[0].value as string;
    formik.setFieldValue('LIST_VALUE', initial);
  }
}, [store.someSearchItems]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:32:45