简体   繁体   English

未处理的拒绝(TypeError):this.props.dispatch(...).then 不是 function

[英]Unhandled Rejection (TypeError): this.props.dispatch(…).then is not a function

I am using redux-thunk and redux-promise together and somehow redux-thunk middleware does not get called and i get an error.我正在一起使用 redux-thunk 和 redux-promise 并且不知何故 redux-thunk 中间件没有被调用并且我得到一个错误。

THIS IS MY SETUP这是我的设置

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom'
import {Provider} from 'react-redux'
import { composeWithDevTools } from 'redux-devtools-extension';
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import promiseMiddleware from 'redux-promise';

import {ThemeProvider} from "@material-ui/core/styles"
import theme from "./components/ui/Theme"
import reducers from './reducers/index'
import './index.css';
import App from './App';

const middleware =[thunk, promiseMiddleware]

const store = createStore(
  reducers,
  composeWithDevTools(applyMiddleware(...middleware))
)



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

THIS IS MY ACTION CREATOR这是我的动作创作者

export const authUser =  () => { 

    const res = axios.get("http://localhost:3002/api/users/auth", {withCredentials: true})
      
    return {type: AUTH_USER, payload: res.data}
}

This is my Higher Order AUTH Component which renders another component and AFTER DISPATCHING ACTION IN ComponentDidMount, based on the results I want to change routes.这是我的高阶 AUTH 组件,它根据我想要更改路由的结果呈现另一个组件并在 ComponentDidMount 中调度操作之后。

import React from 'react'
import {connect} from 'react-redux'
import {withRouter} from 'react-router-dom'

import CircularProgress from '@material-ui/core/CircularProgress';
import {authUser} from '../actions/user'


export default function(WrappedComponent, isRestricted){
    class Auth extends React.Component {

    state = {
        loading: true
    }
    
        componentDidMount() {
        
        this.props.dispatch(authUser()).then(() => {
            this.setState({loading: false})
            
            // if(!this.props.user.isAuth && isRestricted) {
            //     this.props.history.push('/joinus')
            // }
            // else if (this.props.user.isAuth && isRestricted === null) {
            //     this.props.history.push('/')
            // }
        }) 
    }

    render() {

        if(this.state.loading) {
        
            return (
                <CircularProgress />
            )
        }


        return (
            <div>
                <WrappedComponent  {...this.props} />
            </div>
        )
    }  
        
    }

    function mapStateToProps (state) {
        return {
            user: state.user.userData
        }
    }
    
    return  connect(mapStateToProps)(withRouter(Auth))
}

AND FINALLY THIS IS THE ERROR I GET.最后这是我得到的错误。

https://imgur.com/a/nTnv9kh OR https://prnt.sc/tkcs0m https://imgur.com/a/nTnv9khhttps://prnt.sc/tkcs0m

(Unhandled Rejection (TypeError): this.props.dispatch(…).then is not a function ) (未处理的拒绝(TypeError): this.props.dispatch(...).then 不是 function )

If I dont use.then() in ComponentDidMount, then I get undefined.如果我不在 ComponentDidMount 中使用.then(),那么我会得到未定义。 ALSO If I dispatch inside of AXIOS request by adding.then(), this is another error I get另外,如果我通过 add.then() 在 AXIOS 请求内部调度,这是我得到的另一个错误

(Error: Actions must be plain objects. Use custom middleware for async actions.) https://imgur.com/a/czlvHBj OR https://prnt.sc/tkcsqy (错误:操作必须是普通对象。为异步操作使用自定义中间件。)

after adding async await to axios call It worked(I thought It should be handled by middlewares) but now I get another error in my Header component在将异步等待添加到 axios 调用之后它起作用了(我认为它应该由中间件处理)但现在我的 Header 组件中出现另一个错误

    useEffect(() => {
        
        props.dispatch(actions.authUser()).then(() => {
            console.log(props, actions)
            if(props.user.isAuth) setToggleLogOut(true)
        })

        window.addEventListener('scroll', ()=> {
            window.scrollY > 0 ? setToggleHeader(true) : setToggleHeader(false)
        });
    }, [props.value])

    const handleLogOut = () => {
        props.logOutUser(() => {
            setToggleLogOut(false)
        })
    }


.
.
.
.
.
.
.
.


function mapStateToProps (state) {
    return {
        user: state.user.userData
    }
}

export default connect(mapStateToProps)(Header)                                                                                                     

(Unhandled Rejection (TypeError): Cannot read property 'isAuth' of undefined) https://prnt.sc/tkd0bj (未处理的拒绝(TypeError):无法读取未定义的属性“isAuth”) https://prnt.sc/tkd0bj

problem1: The problem is in your axios call.问题1:问题出在您的 axios 电话中。 enter link description here read the documentation.在此处输入链接描述阅读文档。 axios get returns a promise. axios get 返回 promise。 use can use try catch or async await. use 可以使用 try catch 或 async await。

problem2:问题2:

const authData = useSelector(state => state.user)
const [isLoading, setIsLoading] = useState(true)

useEffect(() => {
   if(authData.isAuth) {
      setIsLoading(false)
   }

}, [authData]);

if(isLoading) return <p>loading...</p>

// your rest of code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM