All perfect praise be to Allah, The Lord of the Worlds. I testify that there is none worthy of worship except Allah, and that Muhammad is His slave and Messenger.
Even though masturbation is forbidden, we do not say that it invalidates all the deeds of a person. What invalidates all the deeds of a person is Kufr (disbelief) but not other less serious sins.
Shaykh Ibn Taymiyyah said in his book Minhaaj As-Sunnah:
"Pure disbelief is that which does not leave any faith for the person. They (scholars) said: ‘This is what invalidates all deeds.’ As regards what is less than Kufr, then it may invalidate some deeds, as in the verse about conferring one’s favors in doing good deeds to someone or harming him [i.e. verse 264 of Soorah Al-Baqarah], as that invalidates the charity one spent, but it does not invalidate all his other deeds.” [End of quote]
Rather, the saying that all deeds are invalidated due to a grave major sin other than disbelief is the view of the Mu'tazilah (a deviant sect).
Shaykh Ibn Taymiyyah said in his book Majmoo’ Al-Fataawa:
"They (i.e. the Mu’tazilah) are of the view that all the good deeds of a slave and his faith are all invalidated due to committing one single major grave sin. This is an injustice from which Allah declared Himself free [..] Allah did not make anything a means to invalidate all good deeds except Kufr; in the same manner that He did not make anything a means to invalidate all sins except repentance. The Mu'tazilah and the Khawaarij are of the view that major grave sins invalidate all deeds, even faith.” [End of quote]
However, this does not mean that one can be lenient about indulging in sins when one is alone (behind closed doors) as this is a very serious matter. This is because it may be a reason for invalidating some good deeds whether few or many. On the other hand, it may be a reason for one’s heart to deviate from belief in the future, and a person may die on disbelief or die while committing a bad deed, which means a bad end to his life.
Therefore, a believer must beware of that and strive to protect his private parts from what Allah has forbidden. He must know that Allah is watching him when he is alone and in secret, so he should not act as if Allah is the least important One to see him while sinning.
Allah knows best.