来自 redux-toolkit 的 createAsyncThunk 中的错误响应类型错误
Error response type error in createAsyncThunk from redux-toolkit
什么事?为什么 err 是 typescipt 的错误?存在这样的问题:
ESLint: Unsafe member access .response on an any
value.(@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);
}
},
);
在 TypeScript 中,catch
块中的所有内容在对其进行任何断言之前总是输入 any
- 正如字面意思 any
中的内容可能是 throw
n从 try
块调用的任何函数。你可以 throw 5
在那里,你可以 throw new Error("foo")
在那里,你可以 throw new Date()
在那里,TypeScript 不知道。
因此,您正在那里访问 any.response
- 虽然这是完全有效的 TypeScript,但您已经以警告您的方式配置了 linter。
如果您想进行该访问,请禁用该 lint 规则(假设您在其他任何地方都没有从中获得任何价值),或者在此处执行类型断言,例如 (err as Something).response
。
尽管整个问题与 React 或 Redux 无关。
为了解决这个问题,我听从了作者 phry 的建议
catch (err) {
const hasErrResponse = (err as { response: { [key: string]: string } }).response;
if (!hasErrResponse) {
throw err;
}
return rejectWithValue(hasErrResponse);
}
什么事?为什么 err 是 typescipt 的错误?存在这样的问题:
ESLint: Unsafe member access .response on an any value.(@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);
}
},
);
在 TypeScript 中,catch
块中的所有内容在对其进行任何断言之前总是输入 any
- 正如字面意思 any
中的内容可能是 throw
n从 try
块调用的任何函数。你可以 throw 5
在那里,你可以 throw new Error("foo")
在那里,你可以 throw new Date()
在那里,TypeScript 不知道。
因此,您正在那里访问 any.response
- 虽然这是完全有效的 TypeScript,但您已经以警告您的方式配置了 linter。
如果您想进行该访问,请禁用该 lint 规则(假设您在其他任何地方都没有从中获得任何价值),或者在此处执行类型断言,例如 (err as Something).response
。
尽管整个问题与 React 或 Redux 无关。
为了解决这个问题,我听从了作者 phry 的建议
catch (err) {
const hasErrResponse = (err as { response: { [key: string]: string } }).response;
if (!hasErrResponse) {
throw err;
}
return rejectWithValue(hasErrResponse);
}