【问题标题】:Axios Action in Redux not "thenable"Redux 中的 Axios Action 不是“thenable”
【发布时间】:2017-10-17 21:38:58
【问题描述】:

我有一个完整的 React with Redux 设置。在我的操作文件中,我使用axios 调用第 3 方 API。

将我的表单组件连接到 Redux 存储并尝试调用 POST 操作后,我收到一条错误消息,提示我无法在未定义时调用 then...有趣的是该操作仍然被调用,即表单是在抛出此控制台错误后立即提交给第 3 方的 api。 我查看了许多 S/O 问题以及 axios 和 redux-thunk 文档,但看不到我缺少什么。以下是一些相关代码:

actions.js

import axios from 'axios';
import _ from 'lodash'
import runtimeEnv from '@mars/heroku-js-runtime-env';
import {apiErrorCatcher} from "../../../utils/errorCatcher"
import {toastr} from 'react-redux-toastr'

const env = runtimeEnv();

export function createProfile(data) {
    return dispatch => {
        axios.post( env.REACT_APP_API_URL  + '/api/profile/', data).then( 
            (res) => {
                toastr.success('Profile added', 'Congratulations on adding your profile')
                return res
            }
        )
        .catch(function (error) {
            apiErrorCatcher(error)
            toastr.error('Oops...', 'Unfortunately an error occurred on our side. Please try again later.')
            return error
        })
    }
}

Profile.js

...

handleCreateProfile=()=>{
  this.props.actions.createProfile(this.state.data).then( 
    (res) => {console.log(res)}
  )
}

...

function mapDispatchToProps(dispatch) {
    return { actions: bindActionCreators({createProfile}, dispatch) }
}


export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Profile))

index.js

...
const store = createStore(
  rootReducer,
  composeWithDevTools(
    applyMiddleware(thunk, oidcMiddleware)
  )
);

...
ReactDOM.render(
    <Provider store={store}>
      <OidcProvider store={store} userManager={userManager}>
        <BrowserRouter>
          <MuiThemeProvider>
            <App />
          </MuiThemeProvider>
        </BrowserRouter>
      </OidcProvider>
    </Provider>,
  document.getElementById('root')
);

我认为错误可能与承诺有关,但我不是 100% 有信心。也不知道如何解决这个问题,因为我看不到哪里出错了。

【问题讨论】:

  • 你在哪里得到这个错误?在this.props.actions.createProfile(this.state.data).then(...) ?
  • 您是否尝试在您的操作中返回 Promise? return axios.post(...)
  • 感谢@HiDeo。在阅读您的评论之前,我设法修复了它,但我完全按照您的建议进行了修复。如果您添加您的评论作为答案,我会接受它

标签: javascript reactjs react-redux axios redux-thunk


【解决方案1】:

问题出在你的组件方法中:

this.props.actions.createProfile(this.state.data).then( 
  (res) => {console.log(res)}
)

因为 action 不会返回 promise,所以如果你想记录你的数据,或者 dispatch action 你应该在 action createProfile 中进行。

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2018-09-27
    • 1970-01-01
    • 2021-08-15
    • 2023-03-04
    • 2019-05-20
    • 2019-01-18
    • 2018-11-24
    • 1970-01-01
    相关资源
    最近更新 更多