【问题标题】:Error response type error in createAsyncThunk from redux-toolkit来自 redux-toolkit 的 createAsyncThunk 中的错误响应类型错误
【发布时间】:2021-01-06 08:17:51
【问题描述】:

什么是 h*ll?为什么 err 是 typecipt 的错误?有这样的问题:

ESLint:不安全的成员访问 .response 对任何 值。(@typescript-eslint/no-unsafe-member-access)

这是问题代码的主要部分:

 } catch (err) {
         // Here is problem
          if (!err.response) {
            throw err;
          }
          return rejectWithValue(err);
        }

这里是完整的代码:

export const actionFetchDataUser = createAsyncThunk(
  'data/user',
  async (formVal: TformVal, { rejectWithValue }) => {
    try {
      const GoogleAuth = window.gapi.auth2.getAuthInstance();
      const profileMail = await GoogleAuth.signIn({
        scope: 'profile email',
      });
      const googleEmail = profileMail.getBasicProfile().getEmail();
      if (googleEmail !== formVal.email) {
        throw Error('There is NO email');
      }
      return {
        name: profileMail.getBasicProfile().getName(),
        ava: profileMail.getBasicProfile().getImageUrl(),
      };
    } catch (err) {
     // Here is problem
      if (!err.response) {
        throw err;
      }
      return rejectWithValue(err);
    }
  },
);

【问题讨论】:

    标签: reactjs typescript redux-toolkit


    【解决方案1】:

    在 TypeScript 中,catch 块中的所有内容总是在您对其进行任何断言之前输入 any - 正如字面上的 anything 在从 try 块调用的任何函数中可能是 thrown 一样。你可以在那里throw 5,你可以在那里throw new Error("foo"),你可以在那里throw new Date(),TypeScript 不知道。

    因此,您正在那里访问 any.response - 虽然这是完全有效的 TypeScript,但您已经配置了 linter,它会向您发出警告。 如果您想进行该访问,请禁用该 lint 规则(假设您在其他任何地方都没有从中获得任何价值),或者在此处执行(err as Something).response 之类的类型断言。

    不过,整个问题与 React 或 Redux 无关。

    【讨论】:

    • thnx 我可以通过某种方式发送 err.response 吗? return rejectWithValue(err.response);
    • 是的,但正如我所说,您需要通过astype guard 或类似的方式进行类型断言,然后才能访问该属性
    【解决方案2】:

    为了解决这个问题,我听从了作者 phry 的建议

    catch (err) {
          const hasErrResponse = (err as { response: { [key: string]: string } }).response;
          if (!hasErrResponse) {
            throw err;
          }
          return rejectWithValue(hasErrResponse);
        }
    

    【讨论】:

    • 您能否再解释一下这个答案,或者提供一些有关您选择的文档?谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2020-12-26
    • 2021-11-18
    相关资源
    最近更新 更多