Uncaught Error: Actions must be plain objects?

Uncaught Error: Actions must be plain objects?

Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.....

动作文件:

import $ from 'jquery'

import { phoneVerify } from '../actions/types'

const verifyPhoneAsync = function (verification) {
  return {
    type: phoneVerify,
    payload: verification
  }
}
const verifyPhone = function (phone) {
  $.ajax({
    url: 'api',
    type: 'POST',
    data: { mobile: phone },
    dataType: 'json',
    success: (data) => {
      console.log(data)
    }
  })
}
const verifyOtp = function (phone, otp) {
  return (dispatch) => {
    $.ajax({
      url: 'api',
      type: 'POST',
      data: { mobile: phone, code: otp, devicetoken: 'nil', devicetype: 'nil' },
      dataType: 'json',
      success: (data) => {
        if (data.success === true) {
          localStorage.setItem('MobileNumber', phone)
          const varification = data
          dispatch(verifyPhoneAsync(varification))
        } else {
          console.log('rfg')
          const varification = data
          dispatch(verifyPhoneAsync(varification))
        }
      }
    })
  }
}
export { verifyPhone, verifyOtp }

您在验证手机时忘记了 return,所以出现了这个错误。

您的商店没有配置 redux-thunk 中间件。因此,您的商店不知道如何分派作为函数的操作。

Middleware is not baked into createStore and is not a fundamental part of the Redux architecture

由于您没有添加任何中间件,因此您只能分派对象操作。

首先,当您只有一个商店增强器时,您不需要

当我们想要将多个商店增强器应用到我们的商店时,使用 Compose。

applyMiddleware 是一个存储增强器,用于将中间件添加到我们的调度链中。

注意 applyMiddleware 和 redux 中内置的唯一存储增强器

商店增强器:扩展商店本身

商店增强器只是高阶函数,它为我们的新商店创建者提供了扩展功能。

Middleware: 扩展 store 的 dispatch 方法

而中间件是高阶函数,return 我们的 redux 存储上的新调度方法将在调度新操作时 运行 一些自定义逻辑。

如何使用redux-thunk

等中间件搭建redux store
import { createStore, applyMiddleware } from 'redux'

let middleware = [ thunk ] // add additional middleware to this array

const store = createStore(
  reducer,
  preloadedState,
  applyMiddleware(...middleware)
)

因此您的代码将如下所示:

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import AppContainer from './views/App/container'
import './index.scss'
import reducer from './store/reducers'

let middleware = [ thunk ]

const store = createStore(
  reducer,
   applyMiddleware(...middleware)
)

ReactDOM.render(
   <Provider store={store}>
       <Router history={ browserHistory }>
         <Route path="/" component={ AppContainer }/>
       </Router>
   </Provider>,
   document.getElementById('root')
)

查看完整的文档 applyMiddleware api

您遇到此错误是因为您在 action

中直接使用 ajax 调用(异步调用)

这是因为 Actions 是普通的 JavaScript 对象,并且必须有一个类型 属性 来指示正在执行的操作的类型。

考虑将 redux-thunk 中间件用于 api call 目的以避免此问题。

更多信息:

Redux Async Actions

Redux Thunk