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

使用RTK Query的onQueryStarted时出现未处理Promise拒绝错误求助

解决RTK Query中onQueryStarted引发的解构错误

问题根源

你定义的removeWishlist mutation是build.mutation<void, void>,第二个泛型void意味着这个mutation不需要传入任何参数。但你在onQueryStarted里写了async onQueryStarted({ }, { dispatch, queryFulfilled })——试图解构第一个参数,可这个参数实际是undefined,解构undefined直接触发了TypeError: Cannot destructure undefined。

修复代码

把第一个参数的解构去掉,用占位符(比如_)表示你不需要这个参数就行:

removeWishlist: build.mutation<void, void>({
  query: () => ({
    url: '/remove_wishlist',
    method: 'POST',
    body: 1
  }),
  // 用占位符代替解构,避免处理undefined参数
  async onQueryStarted(_, { dispatch, queryFulfilled }) {
    console.log(queryFulfilled);
    const patchResult = dispatch(
      WishlistApi.util.updateQueryData('homeList', undefined, (draft) => {
        console.log(draft);
      })
    )
    try {
      await queryFulfilled
    } catch {
      patchResult.undo()
    }
  },
  invalidatesTags: ['WISHLIST']
})

补充说明

如果之后这个mutation需要接收参数,只要把第二个泛型从void改成对应类型(比如number),就能正常解构参数了。举个例子:

// 假设需要传入商品ID作为参数
removeWishlist: build.mutation<void, number>({
  query: (productId) => ({
    url: '/remove_wishlist',
    method: 'POST',
    body: productId
  }),
  // 此时可以安全解构参数
  async onQueryStarted(productId, { dispatch, queryFulfilled }) {
    // 这里可以用productId做逻辑处理
  },
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:20:34