【问题标题】:React Native & Redux - Error: Actions must be plain objects. Use custom middleware for async actionsReact Native 和 Redux - 错误:操作必须是普通对象。使用自定义中间件进行异步操作
【发布时间】:2025-12-12 15:40:01
【问题描述】:

我正在尝试使用 Redux 构建一个 react-native 应用程序,但我收到以下来自我的 Actions 文件的错误:

错误:动作必须是普通对象。使用自定义中间件进行异步操作

有人知道这里发生了什么吗?以下是相关代码:

import axios from 'axios' //http client
import {API_URL} from '../utils/constants'

export const FETCH_USER = 'fetch_user'

export const editProfileUser = async (email, password, name, location, aboutMe, memberSince, 
   picture) => {
 try{
 const response = await axios({
 method: 'POST',
 url: `${API_URL}/api/get_token`,
 data: {
  email,
  password
 }
 })
 const {token} = response.data
 const userResponse = await axios({
  method: 'POST',
  url: `${API_URL}/api/edit_user_profile`,
  headers: {
    Authorization: `${token}`
  },
  data: {
    name,
    location,
    aboutMe,
    memberSince,
    picture
  }
})

console.log("userResponse.data", userResponse.data)

return (
  {
    type: FETCH_USER,
    payload: {
      token,
      email,
      password
    }
  }
)


} catch(err){
console.log("Exception in actions/user/editProfileUser err", err)
}
}

【问题讨论】:

    标签: javascript reactjs react-native redux state


    【解决方案1】:

    看起来您正在尝试执行不属于 Redux 的异步操作,您要么需要在外部处理获取您的请求,要么使用像 redux-observableredux-saga 这样的异步 redux 库

    您可以做的是在承诺完成后调用您的操作:

    axios({
          method: 'POST',
          url: `${API_URL}/api/edit_user_profile`,
          headers: {
            Authorization: `${token}`
          },
          data: {
            name,
            location,
            aboutMe,
            memberSince,
            picture
          }
        }).then(({token, email, password}) => {
         // Dispatch your action with the values you want to store
         dispatch(editProfileUser(token, email, password))
    })
    

    来自 redux 文档:

    动作是信息的有效载荷,可从您的 应用到您的商店。他们是唯一的信息来源 商店。

    Action 只负责发送数据,不负责检索数据

    【讨论】: