redux 为什么会出现“RejectwithValue”不是函数的类型错误

nzk0hqpo  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(130)

我正在尝试使用Typescript创建AsyncThunk。在进入catch块时,我返回了rejectwithValue(param)。但是在console.log(action)上-我得到了错误-

error:
    message: "rejectWithValue is not a function"
    name: "TypeError"
    stack: "TypeError: rejectWithValue is not a function\n    at http://localhost:3000/main.105756d7251616c1b9a2.hot-update.js:35:12"
    [[Prototype]]: Object
    meta: {arg: {…}, requestId: '2Z_7_5twR1VcGC2apgQcS', rejectedWithValue: false, requestStatus: 'rejected', aborted: false, …}
    payload: undefined
    type: "LOGIN_USER/rejected"

这是我的createAsynctunk

export const loginUser =  createAsyncThunk(
    types.LOGIN_USER,
    async (param : {payload : object, callback : Function},  rejectWithValue : any) : Promise<AxiosResponse<any, any>> => {
        try{
            let argum : apiArgs = {
                apiUrl : '/someurl',
                method : "POST",
                payload : param.payload
            }
            const response  = await apiCall(argum)
            param.callback()
            return response.data

        }catch(err : any){
            return rejectWithValue(err.response.data)
        }    
    }
)

实际上,我对有效负载感兴趣,由于错误,我得到了未定义的有效负载。

kx7yvsdv

kx7yvsdv1#

请参见payloadCreator,payloadCreator函数的第二个参数是thunkAPI对象,该对象具有rejectWithValue方法。
所以,应该是:

export const loginUser = createAsyncThunk(
  types.LOGIN_USER,
  async (
    param: { payload: object; callback: Function },
    { rejectWithValue }: any
  ): Promise<AxiosResponse<any, any>> => {
    try {
      let argum: apiArgs = {
        apiUrl: '/someurl',
        method: 'POST',
        payload: param.payload,
      };
      const response = await apiCall(argum);
      param.callback();
      return response.data;
    } catch (err: any) {
      return rejectWithValue(err.response.data);
    }
  }
);

相关问题