首页 > 解决方案 > Reactjs + Redux 未处理拒绝(TypeError):无法读取未定义的属性“数据”

问题描述

在使用 react + redux 实现身份验证时,当我尝试使用 async / await 在 redux 的操作中注册用户时,我在 catch 中收到此错误,这是操作的代码:

import axios from 'axios';
import { setAlert } from './alert';
import { REGISTRO_CORRECTO, REGISTRO_FALLIDO } from './types';

// Registro de Usuario
export const registro = ({
  usuario,
  interfac,
  password,
  descripcion
}) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const body = JSON.stringify({ usuario, password, interfac, descripcion });

  try {
    // Conex to backend
    const res = await axios.post('http://localhost:5000/api/usuarios', body, config);

    dispatch({
      type: REGISTRO_CORRECTO,
      payload: res.data
    });
  } catch (err) {
    const errors = err.response.data.errors;

    if (errors) {
      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: REGISTRO_FALLIDO
    });
  }
};

运行提交给我这个错误:

  26 |      payload: res.data
  27 |    });
  28 |  } catch (err) {
> 29 |    const errors = err.response.data.errors;
     | ^  30 | 
  31 |    if (errors) {
  32 |      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));

此致

标签: javascriptreactjsreduxasync-awaitreact-redux

解决方案


您收到错误是因为errors对象数据中不存在该字段。在这种情况下,它应该做一些条件来检查返回对象的格式,然后再引用它来获取数据。

因此,您可以参考下面的检查程序。

  } catch (err) {
    if(err.response.data && err.response.data.message){
       // todo
    }else if(err.response.data && err.response.data.errors){
       // todo
    }

推荐阅读