useRequest 请求状态
17:43说明
useRequest 把页面级请求的三态(loading / data / error)与生命周期收在一起:重复 run() 会先取消上一次未完成请求,过期响应按序号丢弃,组件卸载时自动取消。
使用场景
useRequest 面向「页面里一段会重复发起、可能被打断、需要三态」的请求:
| 场景 | 适合的原因 | 关键用法 |
|---|---|---|
| 详情页进入即加载 | 三态直接驱动骨架屏、空态与错误重试 | { immediate: true } |
| 搜索 / 筛选 / 分页 | 连续触发时旧请求作废,不会覆盖新结果 | 条件变化后调 run() |
| 弹窗 / 抽屉按需加载 | 打开才请求,关闭即可取消 | 打开时 run(),关闭时 cancel() |
| Tab / 路由切换的列表页 | 组件卸载自动取消,避免离开后仍写状态 | 无需额外代码 |
以下片段沿用「示例」中的 api 实例。
进入页面即加载
ts
const detail = useRequest<JsonObject>((ctx) => {
return api.get('/get', null, { signal: ctx.signal } as HttpCallConfig).then((res: any) => {
return (res as HttpResponse).data as JsonObject;
});
}, { immediate: true });条件变化后重新拉取
ts
const keyword = ref<string>('');
const list = useRequest<JsonObject>((ctx) => {
return api.get('/get?q=' + keyword.value, null, { signal: ctx.signal } as HttpCallConfig).then((res: any) => {
return (res as HttpResponse).data as JsonObject;
});
});
/** 搜索词 / 页码变化后调用:上一次未完成请求先被取消,旧响应按序号丢弃 */
const reload = (): void => {
list.run();
};弹窗打开才请求、关闭即取消
ts
const detail = useRequest<JsonObject>((ctx) => {
return api.get('/get', null, { signal: ctx.signal } as HttpCallConfig).then((res: any) => {
return (res as HttpResponse).data as JsonObject;
});
});
const open = (): void => {
detail.run();
};
const close = (): void => {
detail.cancel(); // 不必等组件卸载
};不适合的场景
- 多接口聚合:每个接口都有独立三态时分别建
useRequest;需要一次性合并结果用Promise.all并自行维护状态。 - 表单提交等写操作:通常只需一次 loading 与明确的成功 / 失败分支,直接
await更直观;「后发先至丢弃」的语义对提交没有意义。 - 上传 / 下载进度:进度来自
UploadTask/DownloadTask的onProgressUpdate,useRequest只覆盖 Promise 三态。 - 跨页面共享数据:
useRequest不缓存、不共享,跨页面共享应放到状态层。
示例
useRequest
fetcher 收到 ctx.signal,把它交给 http 的请求即可获得取消能力;run() 返回 Promise<void>,错误已写入 error,无需再 catch。
查看源码
vue
<template>
<ux-button text="通过 useRequest 请求" type="primary" shape="round" @click="run" />
<demo-result :text="summary" />
</template>
<script setup lang="ts">
import { http, useRequest } from '@/uni_modules/uview-pro-x';
import type { HttpCallConfig, HttpResponse } from '@/uni_modules/uview-pro-x';
const api = http.create({ baseURL: 'https://httpbin.org' });
const detail = useRequest<JsonObject>((ctx) => {
return api.get('/uuid', null, { signal: ctx.signal } as HttpCallConfig).then((res: any) => {
return (res as HttpResponse).data as JsonObject;
});
});
const summary = computed<string>(() => {
if (detail.loading.value) return '请求中…';
const err = detail.error.value;
if (err != null) return err.message;
const data = detail.data.value;
if (data == null) return '待发起';
return data['uuid'] as string;
});
const run = (): void => {
detail.run();
};
</script>API
参数
| 参数 | 说明 | 类型 | 默认值 | 版本 |
|---|---|---|---|---|
| fetcher | 业务请求函数,调用时把 ctx.signal 传给请求 | (ctx: UseRequestContext) => Promise<T> | - | - |
| options | 配置项,可省略 | UseRequestOptions | null | null | - |
| options.immediate | 初始化时是否立即执行 | boolean | false | - |
返回值
| 字段 | 说明 | 类型 | 版本 |
|---|---|---|---|
| loading | 是否请求中 | Ref<boolean> | - |
| data | 成功数据,shallowRef 存储 | ShallowRef<T | null> | - |
| error | 失败错误,取消不计入 | Ref<HttpError | null> | - |
| run | 手动执行,先取消上一次未完成请求 | () => Promise<void> | - |
| cancel | 取消当前请求并丢弃其结果 | () => void | - |
注意事项
immediate默认false,需要进入页面即请求时传{ immediate: true }或在onMounted里调用run()。run()内部已消化异常并写入error,返回的 Promise 不需要再catch。- 只有
fetcher里把ctx.signal传给请求才有取消能力;没传时cancel()只能丢弃结果,网络请求仍会继续。 - 连续调用
run()时旧响应按序号丢弃,不会覆盖新数据;loading在最新一次请求结束时复位。 data是shallowRef,整体替换才触发更新,直接改内部字段不会引起视图刷新。- 取消不会写入
error,判断取消请用http.isCancel。