首页 > 解决方案 > 反应:未处理的拒绝(TypeError):无法读取未定义的属性'catch'

问题描述

我正在尝试获取带有 axios 的表单列表进行反应

这是功能

useEffect(() => {
        const fetchData = async () => {
            dispatch({ type: 'SET_STATE', payload: { loading: true } })
            const response = await axios

                .get(`${API_URL}/form`, {
                    userId: localStorage.getItem('userId'),
                    headers: {
                        authorization: localStorage.getItem('userId')
                    }

                })
            console.log(response)
                .catch((err) => {
                    if (err.response.status === 401) history.push('/login')
                    return dispatch({
                        type: 'SET_STATE',
                        payload: { loading: false, error: err.response.data.msg }
                    })
                })
            dispatch({
                type: 'SET_STATE', payload: {
                    data: response.data.form,
                    loading: false,
                },

            })
        }
        fetchData()
        return () => {
            dispatch({ type: 'SET_STATE', payload: { loading: true, error: '' } })
        }
    }, [])

这是减速机

const initialState = {
    data: [],
    loading: false,
    error: '',
}
const formReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'SET_STATE':
            return { ...state, ...action.payload }
        default:
            return state
    }

}

但我收到此错误:

未处理的拒绝(TypeError):无法读取未定义的属性“catch”

标签: reactjsreduxaxios

解决方案


console.log您通过添加betweenget和打破了承诺链catch。使用console.loginthen代替,如下所示:

另外,您正在将 with 混合async/await在一起then。虽然,它response不会像你期望的那样工作。只需使用then链接。

useEffect(() => {
        const fetchData = () => {
           dispatch({ type: 'SET_STATE', payload: { loading: true } })
           axios
               .get(`${API_URL}/form`, {
                    ...
                })

                // add the console in then
                .then(response=>{
                   console.log(response))
                   dispatch({
                     type: 'SET_STATE',
                     payload: {
                       data: response.data.form,
                       loading: false,
                     }
                   })
                 })
                
                .catch((err) => {
                    ...
                })
            
        }
        fetchData()
        return () => {
            dispatch({ type: 'SET_STATE', payload: { loading: true, error: '' } })
        }
    }, [])


推荐阅读