vue-request icon indicating copy to clipboard operation
vue-request copied to clipboard

[Bug Report] isBreak 拦截请求后状态未被正确更新

Open ZiuChen opened this issue 1 year ago • 5 comments

Bug 描述 Bug description

在插件中使用 onBefore 钩子对前置参数进行校验,并选择性拦截请求 拦截后,状态没有被正确重置

代码重现 Reproduce

我编写了一个插件 useBeforePlugin 来辅助完成 onBefore 生命周期中的参数校验与请求拦截功能 但是它并没有按预期工作:

  • id 小于等于 2 时,请求会正常发起
  • 大于 2 时会被 onBefore 拦截,但是可以看到被拦截时的 loadng 状态是错误的(应当为 false)

Demo 链接

CodeSandbox 的 demo 在fork后跑不起来 我用 Stackblitz 编写了一个用于复现的Demo

期望结果 Desired result

当插件在 onBefore 时返回 isBreak 为 true 时:

  • 加载状态应当被重置
  • 响应数据 data 应当被更新为 breakResult 的值

其他信息 Other information

https://github.com/AttoJS/vue-request/pull/225

https://github.com/AttoJS/vue-request/issues/204

ZiuChen avatar Jan 10 '24 07:01 ZiuChen

在 https://github.com/AttoJS/vue-request/pull/225 被 merge 之前,搭配 useBeforePlugin,可以通过这样的操作来完成参数校验与请求拦截:

const { data, loading, mutate } = useRequest(, {
  onBefore(params) {
    // 参数校验
    if(true) {
      nextTick(() => {
        loading.value = false
        // mutate( ... )
      })
      return false
    }
  }
}, [useBeforePlugin])
useBeforePlugin 具体实现

// useBeforePlugin.ts
import { definePlugin } from 'vue-request';

export interface BeforeResult {
  /**
   * 是否阻止请求
   */
  isBreak?: boolean;
  /**
   * 阻止请求时,返回的数据
   */
  breakResult?: any;
}

/**
 * useBeforePlugin
 * 为 onBefore 钩子函数补充拦截请求的能力
 * onBefore 返回 false 时,会阻止请求
 * onBefore 返回对象时,会将对象整个返回给 useRequest
 * @param {Function} onBefore - 请求前的钩子函数
 */
export const useBeforePlugin = definePlugin((_, { onBefore }) => {
  return {
    onBefore(params) {
      // @ts-expect-error
      const res: boolean | BeforeResult = onBefore?.(params);
      console.log('onBefore', res);

      if (res === false) {
        return {
          isBreak: true,
        };
      }

      if (typeof res === 'object' && res !== null) {
        return res;
      }

      return {};
    },
  };
});

ZiuChen avatar Jan 10 '24 08:01 ZiuChen

自定义插件中的 onBefore 钩子添加了isReturn参数,用于处理需要中止请求并返回自定义数据的情况。具体使用参考useCachePlugin

John60676 avatar Jan 10 '24 10:01 John60676

breakResult 直接被干掉了? 那如果有插件使用到了 breakResult 的就都需要调整了

ZiuChen avatar Jan 10 '24 10:01 ZiuChen

这次更新本身就属于 breaking change,所以调整是无法避免的。而且自定义插件使用的人不多

John60676 avatar Jan 10 '24 10:01 John60676

什么时候可以发版解决这个问题呢?👀

ZiuChen avatar Jul 08 '24 07:07 ZiuChen