Objectively, masturbation is a grave sin. Subjectively, freedom can be inhibited so it may not be mortal in some circumstances, but it’s best not to take chances.
Because concupiscence very easily leads people away from God, the Church is always careful in how it advises in this realm. The Church teaches that sex is both unitive and procreative, but that it can’t properly be either of those in exclusivity from each other. In other words, if not procreative it is not unitive. No need to delve into the evidence for the truth of that here except that divorce rates in the US are at 51 percent; divorce rates for NFP couples are less than 3 percent, outside of the statistical margin for error.
So sex is not just for procreation, but it cannot be unifying without being ordered to it. Sex is a glorious thing (I love it!) and is much more beautiful when following Church dictates because it promotes personalism and virtue, as opposed to utilitarianism and selfish gratification.
Your spontaneous thoughts are probably ok (and normal). Just don’t dwell on them and confess them in case there may be lust associated with them. If they are sinful, God’s grace will purify them through confession.