useRequest如何避免Race condition

最近看到React 之 Race Condition这篇文章,里面提到了ahooks中useRequest 也能解决 Race Condition,因此挺好奇怎么解决的

以下是测试代码:

tsx 复制代码
import { useState } from 'react';
import { useRequest } from 'ahooks';

const fakeFetch = (person: string) => {
  return new Promise<string>((res) => {
    setTimeout(() => res(`${person}'s data`), Math.random() * 5000);
  });
};

const Test = () => {
  const [person, setPerson] = useState('Nick');

  const { data, loading } = useRequest(() => fakeFetch(person), {
    refreshDeps: [person],
  });

  const handleClick = (name: string) => () => {
    setPerson(name);
  };

  return (
    <>
      <button onClick={handleClick('Nick')}>Nick's Profile</button>
      <button onClick={handleClick('Deb')}>Deb's Profile</button>
      <button onClick={handleClick('Joe')}>Joe's Profile</button>

      {person && (
        <>
          <h1>{person}</h1>
          <p>{loading ? 'Loading...' : data}</p>
        </>
      )}
    </>
  );
};

export default Test;

找到 ahooks 的源码,位置在 /packages/hooks/src/useRequest/src/Fetch.ts,看到如下代码

ts 复制代码
async runAsync(...params: TParams): Promise<TData> {
	this.count += 1;
	const currentCount = this.count;
	// ...

	try {
		// replace service
		let { servicePromise } = this.runPluginHandler('onRequest', this.serviceRef.current, params);
		// ...

		const res = await servicePromise;

		if (currentCount !== this.count) {
			// prevent run.then when request is canceled
			return new Promise(() => {});
		}

		// ...
		return res;
	} catch (error) {
		if (currentCount !== this.count) {
			// prevent run.then when request is canceled
			return new Promise(() => {});
		}
		// ...
		throw error;
	}
}

从代码中其实可以看出来内部是通过 count 这个变量来控制当前请求函数值的,从这一点也可以看出代码并没有禁用之前的请求函数,也就是说在 useRequest 中,不推荐在异步函数中直接设置值,请看如下测试代码:

tsx 复制代码
import { useState } from 'react';
import { useRequest } from 'ahooks';

const fakeFetch = (person: string) => {
  return new Promise<string>((res) => {
    setTimeout(() => res(`${person}'s data`), Math.random() * 5000);
  });
};

const Test = () => {
  const [person, setPerson] = useState('Nick');
  const [data, setData] = useState('')

  const { loading } = useRequest(() => {
    return fakeFetch(person).then(d => {
      setData(d)
    })
  }, {
    refreshDeps: [person],
  });

  const handleClick = (name: string) => () => {
    setPerson(name);
  };

  return (
    <>
      <button onClick={handleClick('Nick')}>Nick's Profile</button>
      <button onClick={handleClick('Deb')}>Deb's Profile</button>
      <button onClick={handleClick('Joe')}>Joe's Profile</button>

      {person && (
        <>
          <h1>{person}</h1>
          <p>{loading ? 'Loading...' : data}</p>
        </>
      )}
    </>
  );
};

export default Test;

通过测试发现,上面代码还是会不可避免的出现Race Condition,所以在设置值的时候要么使用函数返回的 data,也就是最开始的测试代码那种形式,要么在 onSuccess 中去设置值,如下

tsx 复制代码
const [data, setData] = useState('')

const { loading } = useRequest(() => {
	return fakeFetch(person)
}, {
	refreshDeps: [person],
	onSuccess: (d) => {
		setData(d)
	}
});
相关推荐
threerocks1 小时前
什么?我连 A2A、MCP 都没学会,现在又来了 AG-UI、A2UI.
前端·aigc·ai编程
牛奶2 小时前
如何自己写一个浏览器插件?
前端·chrome·浏览器
亿元程序员2 小时前
为什么Cocos都4.0了还有人用2.x?
前端
MomentYY3 小时前
AI 到底是“懂”,还是在“猜”?
前端·人工智能·ai编程
鹏毓网络科技3 小时前
Cursor Rules 文件配置实战:3 个隐藏参数让我每月少写 40% 样板代码
前端·github
没烦恼3013 小时前
无痕模式下 HTTP\-First 拦截引发的“页面刷新”误判
前端
ZhengEnCi3 小时前
Q02-Vue-React-index.html完全指南
vue.js·react.js·html
文心快码BaiduComate3 小时前
从个人提效到组织提效:Comate辅助构建自我进化的AI研发系统
前端·程序员
hunterandroid3 小时前
Compose 状态管理:remember、rememberSaveable 与状态提升
前端
星栈4 小时前
Dioxus 接数据库最容易写歪的 3 个地方:sqlx + SQLite 怎么接才顺
前端·rust·前端框架