CreateAsyncThunk 期望返回值

时间:2021-07-31 09:18:43

标签: typescript redux redux-toolkit

我正在尝试将以下代码从 js 转换为打字稿,但是我不断收到错误 Expected to return a value at the end of async arrow function。知道这段代码有什么问题吗?

export const loginUser = createAsyncThunk(
  'users/login',
  async ({ email, password }, thunkAPI) : Promise<any> => {
    try {
      const response = await fetch(
        'https://mock-user-auth-server.herokuapp.com/api/v1/auth',
        {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            email,
            password,
          }),
        }
      );
      const data = await response.json();
      console.log('response', data);
      if (response.status === 200) {
        localStorage.setItem('token', data.token);
        return data;
      }
      return thunkAPI.rejectWithValue(data);
    } catch (e) {
      console.log('Error', e.response.data);
      thunkAPI.rejectWithValue(e.response.data);
    }
  }
);

2 个答案:

答案 0 :(得分:2)

您必须在 return thunkAPI.rejectWithValue(e.response.data); 块中catch

如果你在没有 return 的情况下调用它,它什么都不做 - 你会得到这里的错误。

答案 1 :(得分:0)

您在箭头函数中定义了返回类型(它是 createAsyncThunk 函数的第二个参数)。如果您返回默认值,它将被解析。像这样:

export const loginUser = createAsyncThunk(
'users/login',
async ({ email, password }, thunkAPI) : Promise<any> => {
try {
  const response = await fetch(
    'https://mock-user-auth-server.herokuapp.com/api/v1/auth',
    {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        password,
      }),
    }
  );
  const data = await response.json();
  console.log('response', data);
  if (response.status === 200) {
    localStorage.setItem('token', data.token);
    return data;
  }
  return thunkAPI.rejectWithValue(data);
} catch (e) {
  console.log('Error', e.response.data);
  thunkAPI.rejectWithValue(e.response.data);
}
return Promise.resolve();
}
);