React native、redux 和 axios:UnhandledPromiseRejectionWarning

React native, redux and axios : UnhandledPromiseRejectionWarning

我有一个应用程序,您可以在其中创建许多事件,并且我使用 express 和节点 JS 创建了一个 API。在 react-native projet 中,我使用 Axios 来获取 API。但是我的终端出现了这个奇怪的错误:

(node:59293) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): RangeError: Invalid status code: 0
(node:59293) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

当我尝试创建一个事件时,在我的浏览器控制台中我有这个:

Error: Network Error
    at createError (createError.js:15)
    at XMLHttpRequest.handleError (xhr.js:87)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:542)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:378)
    at XMLHttpRequest.js:482
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:242)
    at MessageQueue.js:108
    at guard (MessageQueue.js:46)

我把我的代码贴在这里,也许我哪里错了,

后端部分

import Event from './model';

export const createEvent = async (req, res) => {
  const { title, description } = req.body;
  const newEvent = new Event({ title, description });

  try {
    return res.status(201).json({ event: await newEvent.save() });
  } catch(e) {
    return res.status(e.status).json({ error: true, message: 'Error with event' });
  }
};

export const getAllEvents = async (req, res) => {
  try {
    return res.status(200).json({ events: await Event.find({} )});
  } catch(e) {
    return res.status(e.status).json({ error: true, message: 'Error with all events' });
  }
};

前端部分

api.js

import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:3000/api';

class EventApi {
  constructor() {
    this.path = '/events';
  }

  async fetchEvents() {
    try {
      const { data } = await axios.get(this.path);
      return data.events;
    } catch (e) {
      console.log(e);
    }
  }

  async createEventPost(args) {
    // console.log('nous entrons dans le cadre de la création dun evenement');
    try {
      console.log('nous tryons');
      const res = await axios.post(`${this.path}/new`, { ...args });
      console.log(res);
      console.log('hello world', args);
      return res;
    } catch (e) {
      console.log(e);
      console.log('lol');
    }
  }

}

export {
  EventApi
};

CreateScreen.js

import React, { Component } from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
import DateTimePicker from 'react-native-modal-datetime-picker';
import moment from 'moment';
import { Ionicons } from '@expo/vector-icons';

import { createEvent } from './actions';
import { LoadingScreen } from '../../common';
import Colors from '../../../constants/colors';
import styles from './styles/CreateScreen';
import CreateEventsForm from './components/CreateEventsForm';

@connect(
  state => ({
    event: state.createEvent
  }),
  { createEvent }
)
export default class CreateScreen extends Component {
  static navigationOptions = {
    title: 'Créer un événement',
    header: {
      style: {
        backgroundColor: Colors.whiteColor
      },
      titleStyle: {
        color: Colors.redParty
      }
    },
    tabBar: {
      icon: ({ tintColor }) => (
          <Ionicons name="ios-create" size={25} color={tintColor} />
      )
    }
  }

  state = {
    isDateTimePickerVisible: false,
    date: moment()
  }

  _showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true })

  _handleDateTimePicker = () => this.setState({ isDateTimePickerVisible: false })

  _handleDatePicked = date => {
    this.setState({ date });
    this._handleDateTimePicker();
  }

  _checkTitle() {
    const { date } = this.state;
    if (date > moment()) {
      return moment(date).format('MMMM Do YYYY, h:mm.ss a');
    }
    return 'Choisir une date';
  }

  _checkNotEmpty() {
    const { date } = this.state;
    if (date > moment()) {
      return false;
    }
    return true;
  }

  _createEvent = async values => {
    await this.props.createEvent(values);
    this.props.navigation.goBack();
  }

  render() {
    const { event } = this.props;
    if (event.isLoading) {
      return (
        <View style={styles.root}>
          <LoadingScreen />
        </View>
      );
    } else if (event.error.on) {
      return (
        <View>
          <Text>
            {event.error.message}
          </Text>
        </View>
      );
    }
    return (
      <View style={styles.root}>
        <CreateEventsForm
          createEvent={this._createEvent}
          showDateTimePicker={this._showDateTimePicker}
          checkTitle={this._checkTitle()}
        />
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this._handleDatePicked}
          onCancel={this._handleDateTimePicker}
          mode="datetime"
        />
      </View>
    );
  }
}

acion.js

import { EventApi } from '../../../constants/api';
import { fetchMyEvents } from '../home/actions';

const eventApi = new EventApi();

export const CREATE_EVENT = 'CREATE_EVENT';
export const CREATE_EVENT_SUCCESS = 'CREATE_EVENT_SUCCESS';
export const CREATE_EVENT_ERROR = 'CREATE_EVENT_ERROR';

export const createEvent = args => async dispatch => {
  dispatch({ type: CREATE_EVENT });
  try {
    await eventApi.createEventPost(args);
    dispatch({ type: CREATE_EVENT_SUCCESS });
  } catch (e) {
    return dispatch({ type: CREATE_EVENT_ERROR });
  }
  return await dispatch(fetchMyEvents());
};

reducer.js

import { CREATE_EVENT, CREATE_EVENT_ERROR, CREATE_EVENT_SUCCESS } from './actions';

const INITIAL_STATE = {
  error: {
    on: false,
    message: null
  },
  isLoading: false
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case CREATE_EVENT:
      return {
        ...INITIAL_STATE,
        isLoading: true
      };
    case CREATE_EVENT_SUCCESS:
      return {
        ...INITIAL_STATE,
        isLoading: false
      };
    case CREATE_EVENT_ERROR:
      return {
        error: {
          on: true,
          message: 'Error happened'
        },
        isLoading: false
      };
    default:
      return state;
  }
};

如果您需要更多代码(例如 CreateEventsForm),请随时询问

谢谢!

看起来原来的错误被吞掉了。我为类似问题找到的一种解决方案似乎是删除 react-native 的版本 - https://github.com/mzabriskie/axios/issues/640, but a better approach would to be to discover the original error and then you should be able to address that - https://www.webkj.com/react-native/javascript-error-unhandled-promise-rejection-warning :