基本上我正在使用Vue 3,並且我嘗試分配伺服器傳回的錯誤,例如,如果電子郵件已被其他使用者佔用。第一次工作正常時,我可以將伺服器傳回的訊息指派給我的state.responseErrorMessage
屬性,但是當我嘗試使用新電子郵件重新傳送而不刷新頁面時,ERROR_MESSAGE 突變不會更新!
<script> computed: { ...mapState(['responseSuccessMessage','responseErrorMessage']), }, methods: { ... if( this.errors.firstname.errMsg === null && this.errors.lastname.errMsg === null && this.errors.email.errMsg === null && this.errors.password.errMsg === null && this.errors.passwordConfirm.errMsg === null && this.errors.terms.errMsg === null) { this.$store.dispatch('creatAccount', { firstName: this.firstname, lastName: this.lastname, email: this.email, password: this.password }) setTimeout(() => { // first time submitting the form it display the error message but the second time it doesn't ! console.log(this.responseErrorMessage) }, 2000) } } </script>
export default createStore({ state: { responseSuccessMessage: null, responseErrorMessage: null }, mutations: { SUCCESS_MESSAGE(state, message) { state.responseSuccessMessage = message }, ERROR_MESSAGE(state, message) { state.responseErrorMessage = message setInterval(() => { state.responseErrorMessage = null }, 3000) } }, actions: { async creatAccount({ context, commit, }, user) { try { let result = await axios.post('http://localhost:3001/api/auth/signup', { firstName: user.firstName, lastName: user.lastName, email: user.email, password: user.password }) if (result.status === 201) { commit('SUCCESS_MESSAGE', result.data.message) // state.responseSuccessMessage = result.data.message } } catch (err) { if (err.response.status === 409) { context, commit, // Put this line to avoid eslint errors! commit('ERROR_MESSAGE', err.response.data.message) } else { console.log(err) } } } }, modules: {} })
請不要在你的mutation函數中使用非同步方法(setInterval、setTimeout、promise、ajax...),你可以改變你的程式碼,程式碼
你可能想要將responeErrorMessage重置為null,但是方式不對,你可以這樣寫:
突變:
全球觀察:
你可以試試