The reason why masturbation has been declared forbidden is the wastage of semen, but in this case, it is being gained to be brought into use for conception. Thus, here masturbation is being used for a reason contrary to the reason behind its prohibition. If looked at from this viewpoint, masturbation may be permissible with some degree of undesirability.
‘Allama Nujaim Misri (May Allah shower His mercy on him) (deceased 970 Hijri) has written in Al Bahr Ur Raaiq Sharh Kanz Ud Daqaaiq:
Translation: Even out of Ramadhan, if this act is done only for the sake of pleasure-seeking, then it is not permissible and if the aim is to lull one’s desire, then it is to be hoped there will be no repercussions of this, provided there is no permissible sexual outlet. Also, it is prohibited to seek satisfaction with anybody else’s hand apart from one’s own wife and there should be no nudity. (Al Bahr Ur Raiq, Vol. 2, Pg. No. 475)
The same is given in Tabyeen Ul Haqaaiq, Vol. 2, Pg. No. 16 and in ‘Inaya Sharh Hidayah.