There are many commentators that invoke the story of Onan as a source for the prohibition behind onanism, but there seems to be a distinctly different issue going on that is "evil in the eyes of Hashem."
Ordinarily, the former wife of your brother through widowhood would be expressly forbidden. It is only due to the positive mitzvah of yibum that the kum aseh is docheh the lo sa'aseh because we are commanded "lehakim zera le'achiv." Onan engaged in the "act" of yibum, yet it is expressly stated in the Torah that he engaged in coitus interruptus because he refused to fulfill this positive command. As such, he was not fulfilling the kum aseh and therefore there would BE no heter for him. Thus, Onan wasn't engaged in masturbation, but in an act of gilui arayos with eishes ach!
We find later in the Talmud that some Chachomim decreed that because we are concerned with the "purity of the intent" behind the act they prefer chalitzah over yibum, though this is one of the many splits between Asheknazim (following Rabbeinu Tam) and Sephardim (following Rambam). This would appear to directly mirror the incident with Onan.
Is there a source that interprets Onan's behavior in this manner - as a violation of gilui arayos due to his refusal to fulfill the heter of yibum?